Chinese Documentation : Tutorial: push notifications - iOS client

This is the third of a four-part tutorial on setting up a mobile backend as a service on Amazon and setting up iOS and Android client applications to enable push notification.  See Tutorial: push notifications - LoopBack app for information on setting up the server application.

 

Overview

This article provides information on creating iOS apps that can get push notifications from a LoopBack application.  See Push notifications for information on creating the corresponding LoopBack server application.

The basic steps to set up push notifications for iOS clients are:

  1. Provision an application with Apple and configure it to enable push notifications.

  2. Provide a hook to receive the device token when the application launches and register it with the LoopBack server using the LBInstallation class.

  3. Provide code to receive notifications, under three different application modes: foreground, background, and offline.

  4. Process notifications.

For general information on the Apple push notifications, see Apple iOS Local and Push Notification Programming Guide.  For additional useful information, see Delivering iOS Push Notifications with Node.js.

Prerequisites

Before you start developing your application make sure you've performed all the prerequisite steps outlined in this section.

Configure APN push settings in your server application

Set up messaging credentials for iOS apps

If you have not already done so, create your APNS certificates for iOS apps. After following the instructions, you will have APNS certificates on your system. Then edit config.js in your backend application and look for these lines:

exports.apnsCertData = readCredentialsFile('apns_cert_dev.pem');
exports.apnsKeyData = readCredentialsFile('apns_key_dev.pem');

Replace the file names with the names of the files containing your APNS certificates.  By default, readCredentialsFile() looks in the /credentials sub-directory for your APNS certificates. You can create a credentials directory and copy your pem files into that directory.

 

Icon

To try a sample client application, follow Install and run LoopBack Push Notification app.

To enable push notifications for your own Android app see Add LoopBack iOS SDK as a framework to your own iOS Project.

Install and run LoopBack Push Notification app

If you want to use the sample iOS client app, download the  Push Notification Example iOS app .  Then follow these steps to run the app

  1. Open the apnagent.xcodeproj in Xcode, select targets, under build phases unfold Link Binary with Libraries, and click on '+' to add LoopBack framework(LoopBack iOS sdk).
  2. Edit Settings.plist and update the RootPath to your instance ip. In my case it is - http://ec2-54-184-36-164.us-west-2.compute.amazonaws.com:3000/api

Add LoopBack iOS SDK as a framework to your own iOS Project

Open your XCode project, select targets, under build phases unfold Link Binary with Libraries, and click on '+' to add LoopBack framework.

The LoopBack iOS SDK provides two classes to simplify push notification programming:

  • LBInstallation - enables the iOS application to register mobile devices with LoopBack. 
  • LBPushNotification - provides a set of helper methods to handle common tasks for push notifications.

Initialize LBRESTAdapter

The following code instantiates the shared LBRESTAdapter. In most circumstances, you do this only once; putting the reference in a singleton is recommended for the sake of simplicity. However, some applications will need to talk to more than one server; in this case, create as many adapters as you need.

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
    self.settings = [self loadSettings];
    self.adapter = [LBRESTAdapter adapterWithURL:[NSURL URLWithString:self.settings[@"RootPath"]]];

    // Reference to Push notifs List VC
    self.pnListVC = (NotificationListVC *)[[(UINavigationController *)self.window.rootViewController viewControllers]
                                           objectAtIndex:0];
  
    LBPushNotification* notification = [LBPushNotification application:application
                                         didFinishLaunchingWithOptions:launchOptions];
    
    // Handle APN on Terminated state, app launched because of APN
    if (notification) {
        NSLog(@"Payload from notification: %@", notification.userInfo);
        [self.pnListVC addPushNotification:notification];
    }
    
    return YES;
}

Register the device

- (void)application:(UIApplication*)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData*)deviceToken
{
    __unsafe_unretained typeof(self) weakSelf = self;
    
    // Register the device token with the LoopBack push notification service
    [LBPushNotification application:application
didRegisterForRemoteNotificationsWithDeviceToken:deviceToken
                            adapter:self.adapter
                             userId:@"anonymous"
                      subscriptions:@[@"all"]
                            success:^(id model) {
                                LBInstallation *device = (LBInstallation *)model;
                                weakSelf.registrationId = device._id;
                            }
                            failure:^(NSError *err) {
                                NSLog(@"Failed to register device, error: %@", err);
                            }
     ];
...
}

- (void)application:(UIApplication*)application didFailToRegisterForRemoteNotificationsWithError:(NSError*)error {
    // Handle errors if it fails to receive the device token
        [LBPushNotification application:application didFailToRegisterForRemoteNotificationsWithError:error];
}

Handle received notifications

- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo {
    // Receive push notifications
    LBPushNotification* notification = [LBPushNotification application:application
                                          didReceiveRemoteNotification:userInfo];
    [self.pnListVC addPushNotification:notification];
}