How can I implement Apple Push Notification Service on iOS Application?

前端 未结 3 1872
余生分开走
余生分开走 2020-12-18 12:00

Is there any sample project showing how to integrate APNS on IPhone, and how to get deviceToken?

相关标签:
3条回答
  • 2020-12-18 12:15
    - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
     // Register for Push Notitications, if running on iOS 8
    if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 8.0){
        [[UIApplication sharedApplication] registerUserNotificationSettings:[UIUserNotificationSettings settingsForTypes:(UIUserNotificationTypeSound | UIUserNotificationTypeAlert | UIUserNotificationTypeBadge) categories:nil]];
        [[UIApplication sharedApplication] registerForRemoteNotifications];
     }else{
        [application registerForRemoteNotificationTypes:(UIRemoteNotificationTypeAlert | UIRemoteNotificationTypeBadge | UIRemoteNotificationTypeSound)];
    }
      return YES;
    }
    #pragma mark
    #pragma mark -- Push Notification Delegate Methods
    - (void)application:(UIApplication *)application didRegisterUserNotificationSettings:   (UIUserNotificationSettings *)notificationSettings{
    //register to receive notifications
    [application registerForRemoteNotifications];
    }
    -(void)application:(UIApplication*)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData*)deviceToken{
    // Prepare the Device Token for Registration (remove spaces and < >)
     NSString* devToken = [[[[deviceToken description]
                  stringByReplacingOccurrencesOfString:@"<"withString:@""]
                 stringByReplacingOccurrencesOfString:@">" withString:@""]
                stringByReplacingOccurrencesOfString: @" " withString: @""];
    NSLog(@"My token is: %@", devToken);
    }
    -(void)application:(UIApplication*)application didFailToRegisterForRemoteNotificationsWithError:(NSError*)error{
    //  NSLog(@"Failed to get token, error: %@", error);
    }
    
    - (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo{
    NSLog(@"%s..userInfo=%@",__FUNCTION__,userInfo);
    /**
     * Dump your code here according to your requirement after receiving push
     */
     }
    
    0 讨论(0)
  • 2020-12-18 12:18

    there are a few simple steps you need to follow:

    1. in your app delegate's didFinishLaunchingWithOptions you should register for remote notifications. notice that apple's documentations suggests to register each time the app runs since the token may change from time to time. you do this by calling:

      [[UIApplication sharedApplication] registerForRemoteNotificationTypes:UIRemoteNotificationTypeAlert | UIRemoteNotificationTypeBadge | UIRemoteNotificationTypeSound];
      
    2. after registering for remote notifications a method in your app delegate will be called which had been passed the token, you need to implement this method in your app delegate and send the token to your server (that will send you notifications). the method will look like this:

      - (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken{
      
          NSLog(@"device token is: %@",deviceToken);
          [server sendToken:deviceToken];
      }
      

    you should also implement this as well:

        -(void)application:(UIApplication *)application didFailToRegisterForRemoteNotificationsWithError:(NSError *)error{}
    
    1. you need to handle notifications once you get them. there are few different scenarios in which you handle received notifications (the app is in the background or foreground etc.), the method that handles a notification if the app is in the foreground when you receive it should be implemented in the app delegate. this is it:

      -(void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo{
          NSLog(@"received notification");
          //handle the notification here
      }
      

    to learn more about the userInfo structure and cover all the different scenarios read carefully http://developer.apple.com/library/mac/#documentation/NetworkingInternet/Conceptual/RemoteNotificationsPG/ApplePushService/ApplePushService.html. this was just the gist of things :)

    0 讨论(0)
  • 2020-12-18 12:22

    Here is brief document about - How to enable and send push notification in iOS.

    Enabling Push Notifications

    The first step in setting up push notifications is enabling the feature within Xcode 8 for your app. Simply go to the project editor for your target and then click on the Capabilities tab. Look for Push Notifications and toggle its value to ON:

    Toggle Capability

    Xcode should display two checkmarks indicating that the capability was successfully enabled. Behind the scenes, Xcode creates an App ID in the Developer Center and enables the Push Notifications service for your app.

    Registering Devices

    Devices need to be uniquely identified to receive push notifications.

    Every device that installs your app is assigned a unique device token by APNs that you can use to push it at any given time. Once the device has been assigned a unique token, it should be persisted in your backend database.

    A sample device token looks like this:

    5810F4C8C2AF5F7 F7 D6AF71A 22745D0FB50DED 665E0E882 BC5370D9CF0A F19E16  
    

    To request a device token for the current device, open AppDelegate.swift and add the following to the didFinishLaunchingWithOptions callback function, before the return statement:

    // iOS 10 support
    if #available(iOS 10, *) {  
        UNUserNotificationCenter.current().requestAuthorization(options:[.badge, .alert, .sound]){ (granted, error) in }
        application.registerForRemoteNotifications()
    }
    // iOS 9 support
    else if #available(iOS 9, *) {  
        UIApplication.shared.registerUserNotificationSettings(UIUserNotificationSettings(types: [.badge, .sound, .alert], categories: nil))
        UIApplication.shared.registerForRemoteNotifications()
    }
    // iOS 8 support
    else if #available(iOS 8, *) {  
        UIApplication.shared.registerUserNotificationSettings(UIUserNotificationSettings(types: [.badge, .sound, .alert], categories: nil))
        UIApplication.shared.registerForRemoteNotifications()
    }
    // iOS 7 support
    else {  
        application.registerForRemoteNotifications(matching: [.badge, .sound, .alert])
    }
    

    In iOS 10, a new framework called UserNotifications was introduced and must be imported in order to access the UNUserNotificationCenter class.

    Add the following import statement to the top of AppDelegate.swift:

    import UserNotifications 
    

    Next, go to the project editor for your target, and in the General tab, look for the Linked Frameworks and Libraries section.

    Click + and select UserNotifications.framework:

    Next, add the following callbacks in AppDelegate.swift which will be invoked when APNs has either successfully registered or failed registering the device to receive notifications:

    // Called when APNs has assigned the device a unique token
    func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {  
        // Convert token to string
        let deviceTokenString = deviceToken.reduce("", {$0 + String(format: "%02X", $1)})
    
        // Print it to console
        print("APNs device token: \(deviceTokenString)")
    
        // Persist it in your backend in case it's new
    }
    
    // Called when APNs failed to register the device for push notifications
    func application(_ application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: Error) {  
        // Print the error to console (you should alert the user that registration failed)
        print("APNs registration failed: \(error)")
    }
    

    It's up to you to implement logic that will persist the token in your application backend. Later in this guide, your backend server will connect to APNs and send push notifications by providing this very same device token to indicate which device(s) should receive the notification.

    Note that the device token may change in the future due to various reasons, so use NSUserDefaults, a local key-value store, to persist the token locally and only update your backend when the token has changed, to avoid unnecessary requests.

    Run your app on a physical iOS device (the iOS simulator cannot receive notifications) after making the necessary modifications to AppDelegate.swift. Look for the following dialog, and press OK to permit your app to receive push notifications:

    Alert Dialog

    Within a second or two, the Xcode console should display your device's unique token. Copy it and save it for later.

    Prepare to Receive Notifications

    Add the following callback in AppDelegate.swift which will be invoked when your app receives a push notification sent by your backend server:

    // Push notification received
    func application(_ application: UIApplication, didReceiveRemoteNotification data: [AnyHashable : Any]) {  
        // Print notification payload data
        print("Push notification received: \(data)")
    }
    

    Note that this callback will only be invoked whenever the user has either clicked or swiped to interact with your push notification from the lock screen / Notification Center, or if your app was open when the push notification was received by the device.

    It's up to you to develop the actual logic that gets executed when a notification is interacted with. For example, if you have a messenger app, a "new message" push notification should open the relevant chat page and cause the list of messages to be updated from the server. Make use of the data object which will contain any data that you send from your application backend, such as the chat ID, in the messenger app example.

    It's important to note that in the event your app is open when a push notification is received, the user will not see the notification at all, and it is up to you to notify the user in some way. This StackOverflow question lists some possible workarounds, such as displaying an in-app banner similar to the stock iOS notification banner.

    Generate an APNs Auth Key

    Open the APNs Auth Key page in your Developer Center and click the + button to create a new APNs Auth Key.

    In the next page, select Apple Push Notification Authentication Key (Sandbox & Production) and click Continue at the bottom of the page.

    Apple will then generate a .p8 key file containing your APNs Auth Key.

    Download the .p8 key file to your computer and save it for later. Also, be sure to write down the Key ID somewhere, as you'll need it later when connecting to APNs.

    Send Push Notifications

    Now, look at here to understand, APNS flow: How do iOS Push Notifications work?

    0 讨论(0)
提交回复
热议问题