. . .

iOS Tutorial Push

In this tutorial we will write an iOS app with the ability to receive push messages. It's irrelevant whether you are using Objective-C or Swift, because we support both programming languages by providing SDKs for each and the code snippets within this tutorial are provided in both languages.

At 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 could do this by creating and configuring the App ID in your Apple Developer Account, but the easier way is to let Xcode do it.

Choose your app target in the Xcode project, go to Capabilities and switch 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 is needed 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 will 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, simply register by clicking "Not having an account yet?”.

    images/download/attachments/8390930/SS_apiOmat_login.PNG

  2. You are now logged into the dashboard. If you haven‘t created a backend yet, you will be asked to create one with a dialogue that asks for a backend name and description.

    images/download/attachments/8390930/SS_apiOmat_UsingServerCode_AppName.PNG

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

  4. A dialogue will appear. 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. Then, 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.

You are now 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 on which your app is installed.

Also add the following method to the AppDelegate to be notified when the registration 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. In a simulator the registration won't work.

After you 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!

For testing we will 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/8390930/SS_apiOmat_My_Module_Push.PNG

  4. Click “Send”.

  5. Have a look on your iOS device for the push notification.

* link only available in Enterprise Documentation