Guide d'intégration iOS

Carma iOS Integration Guide

Rev pA3.

 

Contents

About this document. 3

Change notes: 3

How Apple’s push notification service works. 4

Integration. 4

Getting started. 4

Configuring an App for Push Notifications. 4

Enabling the Push Notification Service. 4

Registering for Push Notifications. 5

Register for push notifications. 5

Registering your app in Carma. 9

Creating an SSL Certificate and a P12 file. 9

Registering the App in Carma. 11

Handling Push Notifications. 12

What Happens When You Receive a Push Notification?. 12

Compost Content. 12

Testing and troubleshooting. 13

 

 

 

 

About this document

This document describes how to integrate Carma with Apple’s push notification service (APNS) for iOS.

 

Change notes:

pA1                        first version

pA2                        changed the URL and payload layout for device registration.

pA3       Updated example code

 

 

 

How Apple’s push notification service works

Apple’s system considers 3 parties:

  • The client application
  • Apple’s push notification service
  • a 3rd party server, in this case Carma.

When a user installs a push-enabled application and starts it for the first time, it ask the user for permission of receiving push notifications. Once the user agrees, as soon as you decide to send your users a notification, a succession of actions will be triggered:

  • Carma sends the push notification to Apple’s push notification servers.
  • These servers relay the message to all your registered mobile applications.
  • Messages are queued and stored for devices that are offline.
  • As soon as a device comes back online, APNS servers relay the queued message.
  • The messages are received and presented according to the platform-specific implementation.

 

Integration

The steps for integration are as follows:

Getting started

 

Three main tasks must be performed in order to send and receive a push notification:

  1. The app must be configured properly and registered with the Apple Push Notification Service (APNS) to receive push notifications upon every start-up.
  2. The app is registered in Carma using the appName, App id and development and/or production certificate.
  3. A server must send a push notification to APNS directed to one or more specific devices.
  4. The app must receive the push notification; it can then perform tasks or handle user actions using callbacks in the application delegate.

 

Configuring an App for Push Notifications

Before you begin, you will need to have an iOS app to which you want to send push notifications.

This push notifications tutorial assumes that  Xcode 7.3 or later is used as the IDE.

 

Enabling the Push Notification Service

The first step is to change the App ID. Go to App Settings -> General and change Bundle Identifier to something unique. Next, you need to create an App ID in your developer account that has the push notification entitlement enabled. Luckily, Xcode has a simple way to do this. Go to App Settings -> Capabilities and flip the switch for Push Notifications to On.
Behind the scenes, this creates the App ID in your member center if it does not exist already, and then adds the push notifications entitlement to it. If any issues occur, or if you prefer, manually create the App ID or add the push notifications entitlement in the member center by using the + or Edit buttons.

Registering for Push Notifications

There are three steps to register for push notifications. You first must obtain the user’s permission to show any kind of notification, after which you can register for remote notifications. If all goes well, the system will then provide you with a device token, which you can think of as an “address” to this device. Third, the application needs to register the device token with Carma’s servers.

Obtaining User Permission

In your apps AppDelegate add the following method:

func registerForPushNotifications(application: UIApplication) {
let notificationSettings = UIUserNotificationSettings(
forTypes: [.Badge, .Sound, .Alert], categories: nil ) application.registerUserNotificationSettings(notificationSettings)

}

Register for push notifications

Add a call to registerForPushNotifications(_:) as the first line application(_:didFinishLaunchingWithOptions:launchOptions:)

func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {  registerForPushNotifications(application)

//…

}
Add this method inside AppDelegate:

func application(application: UIApplication, didRegisterUserNotificationSettings notificationSettings: UIUserNotificationSettings) {
if notificationSettings.types != .None {
application.registerForRemoteNotifications()
}
}

Registering the device and token in Carma

Before implementing this functionality, you need the following information about your Carma account:

  1. The URL of the server where your account is.
  2. A customerId
  3. Username
  4. Password

You can request this information from your account manager or by sending an email to support@compost.se

Once a device has registered with APNS successfully, the didRegisterForRemoteNotificationsWithDeviceToken method in the app delegate will be called with the token.

func application(application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: NSData) {

print(“Device Token:”, tokenString)

}

The registration might fail, so you should also implement the following app delegate function for this condition:

func application(application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: NSError) {

print(“Failed to register:”, error)

}

 

This token needs to be registered in Carma along with the appId and an originalid of you choosing. The originalid is an identifier or the user in you system. It could be an email address or a primary key of the user in your database. If you do not have an originalid for the current user in your app, you may use the token as originalId.

NOTE! You can have many tokens registered for the same originalId, i.e. a user can use the app in an iPad and an iPhone at the same time and have a notification sent to both.

This is done by issuing a PUT request to:

https:///rest/<customerid>/apps//pushdevices

with a json payload containing at the minimum:

  • deviceToken
  • originalId

NOTE! Even if they are the same both values must be provided.

A minimal version of the payload would look like this:

{

“originalId”: “abcabc123123”,

“deviceInfo”: [{“devicetoken”: “abc123abc123kmlkmlkml”}]

}

 

 

 

In this payload you can also add other information about the user that should be transferred to Carma. Below is the full list of available properties.

{

“listId”: 1000000005,

“country”: null,

“originalId”: “abcabc123123”,

“firstName”: “lars”,

“lastName”: “hansson”,

“middleName”: null,

“emailAddress”: “lars@compost.se”,

“title”: null,

“dateOfBirth”: null,

“city”: null,

“zipcode”: null,

“sex”: null,

“mobileNumber”: null,

“optOutDate”: null,

“dateOfInvalidation”: null,

“optOutMobileDate”: null,

“active”: true,

“properties”: {

“food”: “meat”,

“drink”: “tea”

}

,

“deviceInfo”: [

{

“devicetoken”: “abc123abc123kmlkmlkml”,

“manufacturer”: “apple”,

“model”: “iphone 6”,

“osVersion”: “9.2”,

“country”: “Sweden”,

“dateOfInvalidation”: null,

“invalidationType”: 0

}

]

}

The resource uses Basic Auth for authentication and need you to set the Content-Type and Accept headers to “application/json”

The same struct is used to return info on the device, but it is then appended with all devices that is connected to the contact.

The following code can be used for the registration:

func saveClientProfile(token:NSData, originalId:String, appId:String, serverUrl:String,

username:String, password:String, ) {

let request: NSMutableURLRequest = NSMutableURLRequest()
request.URL = NSURL(string:url)
request.HTTPMethod = “PUT”
let loginstring = NSString(format: “%@:%@”,username,password)
let logindata:NSData! = loginstring.dataUsingEncoding(NSUTF8StringEncoding)
let base64 = logindata.base64EncodedStringWithOptions([])
let dict:NSMutableDictionary  = NSMutableDictionary()
dict.setObject(appId, forKey: “appId”)
dict.setObject(originalId, forKey: “originalId”)

let devicetoken:NSMutableDictionary  = NSMutableDictionary()

devicetoken.setObject(token, forKey: “deviceToken”)

var set:Set = [devicetoken]

dict.setObject(devicetoken, forKey; “deviceInfo”)

let data:NSData = try! NSJSONSerialization.dataWithJSONObject(dict, options: NSJSONWritingOptions.PrettyPrinted)
request.HTTPBody = data
request.addValue(“Basic ” + base64, forHTTPHeaderField: “Authorization”)
request.addValue(“application/json”, forHTTPHeaderField: “Accept”)
request.addValue(“application/json”, forHTTPHeaderField: “Content-Type”)
NSURLConnection.sendAsynchronousRequest(request, queue: NSOperationQueue(), completionHandler: { (response:NSURLResponse?, data:NSData?, error:NSError?) -> Void in
var perror:AutoreleasingUnsafeMutablePointer<NSError?> = nil
if (data != nil) {
var datastring = NSString(data:data!, encoding:NSUTF8StringEncoding)
do {
let jsonResult :NSDictionary! = try NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions.MutableContainers) as? NSDictionary
if (jsonResult != nil) {        } else {            }
} catch {
}
}
}
)
}

Invalidation of a devicetoken.

If you want to remove a registration of a devicetoken for an OriginalId you can issue a request to

This is done by issuing a PUT request to:

https:///rest/<customerid>/apps//pushdevices/invalidation

with a json payload containing at the minimum:

  • deviceToken
  • originalId,

{

“deviceInfo”:[{“devicetoken”: “abc123abc123kmlkmlkml_2”}],

“originalId”:”abcabc123123″

}

 

NOTE! Even if ththe originalId and devicetoken are the same, both values must be provided.

 

Retrieving information about a contact

If you want to retrieve the information connected to a contact you can issu a GET request to

https:///rest/<customerid>/apps//pushdevices/

You will receive the same struct as when you register a device.  It will contain a list of all devices registered on the originalId. If you have imported information by other means i.e, via scheduledimport on the list, this data will also retreived.

 

 

 

Registering your app in Carma

Before Carma can send notifications to your app, the app needs to be registered in Carma together with the development and production certificate for that app.

Creating an SSL Certificate and a P12 file

In your member center, go to Certificates, Identifiers & Profiles -> Identifiers -> App IDs and find the App ID for your app. Under Application Services, Push Notifications should be Configurable:

Click Edit and scroll down to Push Notifications:

In Development SSL Certificate, click Create Certificate and follow the steps to create a CSR. Once you have your CSR, click continue and Generate your certificate using the CSR. Finally, download the certificate and run it, which should add it to your Keychain, paired with a private key:

Back in the member center, your App ID should now have push notifications enabled for development:

There is one last thing you need before you close Keychain Access. Right-click on your new push certificate and choose Export:

Export the certificate as a P12 file. Remember the password you give the file since you will need it when registering the app Carma. Repeat the procedure above for your production certificate.

 

Registering the App in Carma

Carma Account

TO send a push you will need an account in Carma, where you will have received the following information:

  • Username
  • Password
  • Server URL

Setup App in Carma:

 

Click on Account Setting in the left hand menu and then choose Push Apps under Manage

Click Create new,  check the iOS radio button  and you will see the following dialog where you enter the information

Fill in the fields with name, appId and attach the certificate files that you produced earlier. Now Carma is ready to start sending notifications to your application!

 

 

 

 

Handling Push Notifications

A compost push message contains the following fields:

  • alert – intended to be the line shown next to the icon in the notification
  • message – intended to be the line shown under the first in the notification
  • url – the url pointing to the actual rich content of the push
  • pushreadurl – call this URL to mark the push as read in Carma.
  • source – will always by “carma”. This should be used to distinguish between push messages that comes from other systems than carma. A game for example might have high-score system in place that will notify a player

It’s important to remember that it’s up to the application developer to decide how these fields should be used.  Our iOS client is now registered with APNS, and our server can begin sending messages to devices running our client using the provided app Id and APNS certificates

What Happens When You Receive a Push Notification?

When your app receives a push notification, a method in UIApplicationDelegate is called.

The notification needs to be handled differently depending on what state your app is in when it’s received:

  • If your app wasn’t running and the user launches it by tapping the push notification, the push notification is passed to your app in the launchOptions of application(_:didFinishLaunchingWithOptions:).
  • If your app was running and in the foreground, the push notification will not be shown, but application(_:didReceiveRemoteNotification:) will be called immediately.
  • If your app was running or suspended in the background and the user brings it to the foreground by tapping the push notification, application(_:didReceiveRemoteNotification:) will be called.

Compost Content

The content of a push message is not sent in the push itself, but is located at server side where the url in message is pointing. Content is usually a page of html that is generated for the particular device, user by a template of the server side. It could however be XML or other text-based formats as defined by template.

The most common way to handle content is to simply open an UIWebView and pointing it to the url, making it display the page. The developer could however choose to handle it in different ways.

If you don’t want to fetch the rich content you can mark the push as opened in carma by issuing  a GET request to the pushreadurl.

 

Testing and troubleshooting

Once you have done integration, perform the following tests.

  • Install the application on a new device
  • Notice that the number of recipients increases for each time you do this. If not, check that the id’s you supply are correct. Check also that the appid you gave when registering the application is the same as the package given in the top of your manifest.
  • If the list does grow, test a simple push while the application is running. If a notification does not show up after a few minutes, make sure that you have given the correct api-key when registering the app in Carma.
  • Once the above works correct, verify that the notifications show up when sending a push even though the application is not running.