. . .

iOS Tutorial Push

In this tutorial we'll write an iOS app with the ability to receive push messages. You can use either Objective-C or Swift for this tutorial, as ApiOmat supports both programming languages with SDKs and we've included the code snippets for both as well.

First, we have to register at the Apple Push Notification Service (APNS) to be able to receive push notifications.

1 Enabling Apple's Push Notification Service

Initially, you need to create an App ID in your developer account that has the push notification entitlement enabled. You can do this by creating and configuring the App ID in your Apple Developer Account, but it's easier to let Xcode do it.

Choose your app target in the Xcode project, go to Capabilities and turn on Push Notifications.

images/bytebucket.org/apinaut/pushtest/raw/f6051327393b82a7c99ac7b96a3e9c5c9055c341/Other-Tasks/Tutorial-iOS-Push/SS_Enable_Push_Xcode.png

Behind the scenes, Xcode creates the App ID in your member center and adds the push notifications entitlement to it.

To check if it worked, login into Apples' member center and choose your App ID in Certificates, Identifiers & Profiles area. You should see a configuration like this:

images/bytebucket.org/apinaut/pushtest/raw/f6051327393b82a7c99ac7b96a3e9c5c9055c341/Other-Tasks/Tutorial-iOS-Push/SS_App_ID_With_Enabled_Push.png

Click Edit and scroll down to Push Notifications. Here, you can obtain the SSL Certificate that you need for configuring the backend later. Follow these steps to do that:

  1. In Development SSL Certificate, click Create Certificate and follow the steps to generate and download the certificate.

    images/bytebucket.org/apinaut/pushtest/raw/f6051327393b82a7c99ac7b96a3e9c5c9055c341/Other-Tasks/Tutorial-iOS-Push/SS_Create_SSL_Certificate.png

  2. Run (double-click) the downloaded certificate to add it to your Keychain.

  3. Right-click on the generated certificate in your Keychain and choose Export. You will be prompted to enter a password. This generates a .p12 file, which you'll use for configuring the backend in the next step.

2 Setting up the Backend

  1. Log into your account. If you don‘t have an account yet, sign up by clicking "Don't have an account yet?”.

    images/download/attachments/10719119/gettingStarted_login.png

  2. You're now logged into the dashboard. If you haven‘t created a backend yet, you will be asked to create one. Enter a name and description for your backend.

    images/download/attachments/10719119/push_newBackend.png

  3. On the first dashboard page, called the module market, you see all the available modules. Add the Push Module to your backend by clicking "+" right next to the module's name.

  4. When the dialogue appears, upload the .p12 file that we have created in the last step in the field APNS certificate, enter the password and confirm with 'Save'.

    Passwordless Certificates

    Please note that passwordless certificates are not supported when sending push notifications with ApiOmat.

    images/bytebucket.org/apinaut/pushtest/raw/f6051327393b82a7c99ac7b96a3e9c5c9055c341/Other-Tasks/Tutorial-iOS-Push/SS_configure_push_module.png

  5. Go to the SDK tab, choose Objective-C or Swift and download the SDK. The downloaded .ZIP archive contains all classes and resources you'll need.

  6. Unzip the .ZIP archive and drag the unzipped folder into your Xcode project.

Now you're ready to write some code.

3 Registering for Push Notifications

Now in your app's code, you need to register for push notifications to be able to receive them.

First, you need to ask for the user’s permission. Open the project's AppDelegate and add the following code to do so:

Swift
func registerForPushNotifications(application: UIApplication) {
let notificationSettings = UIUserNotificationSettings(forTypes: [.Badge, .Sound, .Alert], categories: nil)
application.registerUserNotificationSettings(notificationSettings)
}
Objective-C
- (void)registerForPushMotifications:(UIApplication *)app {
UIUserNotificationSettings *settings = [UIUserNotificationSettings
settingsForTypes:(UIUserNotificationTypeAlert
| UIUserNotificationTypeBadge
| UIUserNotificationTypeSound) categories:nil];
[app registerUserNotificationSettings:settings];
}

Call this method in AppDelegates didFinishLaunchingWithOptions method. Now, when you start the app, the following prompt should appear that asks the user for permission.

images/bytebucket.org/apinaut/pushtest/raw/f6051327393b82a7c99ac7b96a3e9c5c9055c341/Other-Tasks/Tutorial-iOS-Push/SS_allow_push_in_app.png

When user accepts or declines permissions, the delegate method application(_:didRegisterUserNotificationSettings:) gets called. Add this method inside AppDelegate:

Swift
func application(application: UIApplication, didRegisterUserNotificationSettings notificationSettings: UIUserNotificationSettings) {
if notificationSettings.types != .None {
application.registerForRemoteNotifications()
}
}
Objective-C
- (void)application:(UIApplication *)application didRegisterUserNotificationSettings:(UIUserNotificationSettings *)notificationSettings {
if (notificationSettings.types != UIUserNotificationTypeNone) {
[application registerForRemoteNotifications];
}
}

Here, you first check whether the user accepted any notification permissions. If that's the case, you register for notifications.

If the registration was successful, another delegate method gets called, where you have access to the device token:

Swift
func application(application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: NSData) {
let tokenChars = UnsafePointer<CChar>(deviceToken.bytes)
var tokenString = ""
for i in 0..<deviceToken.length {
tokenString += String(format: "%02.2hhx", arguments: [tokenChars[i]])
}
print("Device Token:", tokenString)
}
Objective-C
- (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)devToken {
const unsigned *tokenBytes = [devToken bytes];
NSString *tokenString = [NSString stringWithFormat:@"%08x%08x%08x%08x%08x%08x%08x%08x",
ntohl(tokenBytes[0]), ntohl(tokenBytes[1]), ntohl(tokenBytes[2]),
ntohl(tokenBytes[3]), ntohl(tokenBytes[4]), ntohl(tokenBytes[5]),
ntohl(tokenBytes[6]), ntohl(tokenBytes[7])];
NSLog(@"Device token: %@", tokenString);
}

This device token is like a phone number, it contains information that enables APNs to locate the device where your app is installed.

Also add the following method to the AppDelegate to be notified if the registration has failed:

Swift
func application(application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: NSError) {
print("Failed to register:", error)
}
Objective-C
- (void)application:(UIApplication *)app didFailToRegisterForRemoteNotificationsWithError:(NSError *)error {
NSLog(@"Failed to register %@", error);
}

Be aware that you need to run the application on a real device to test this, as the registration won't work in a simulator.

After you've successfully received the device token, the only thing left to do is to create a user and attach the device token:

Swift
user.deviceToken = deviceToken
user.save { (error) in
// Handle error.
}
Objective-C
[user setDeviceToken:deviceToken];
[user saveAsyncWithBlock:^(NSError *error) {
// Handle error.
}];

Let's go!

To test whether it works, we'll send a push message from the dashboard to our device

  1. Start the app on your iOS device.

  2. Switch back into the dashboard of ApiOmat.

  3. Click the tab My Modules and then the button “Push”.

    images/download/attachments/10719119/push_doPush.png

  4. Click “Send”.

  5. Check your iOS device for the notification.

* link only available in Enterprise Documentation