{"_id":"5b4dcdfc666e630003bca202","project":"55dd9f2e0efd5821000d54d9","version":{"_id":"55dd9f4dab0e4d210045aae9","__v":45,"project":"55dd9f2e0efd5821000d54d9","createdAt":"2015-08-26T11:13:17.024Z","releaseDate":"2015-08-26T11:13:17.024Z","categories":["55dd9f4dab0e4d210045aaea","55ddb5fa9067202b00ddff6f","55e0472c6bad670d0081f213","55e04764a44fae0d00214671","55e047a9a44fae0d00214672","55e047b258c5460d0076a9a7","55e95e337fc27b2d00d32cf2","55e979bda7ca823900ad549a","55edb8c18dcb210d0056900b","55f0365c8563861700a33765","55f03677d58f9b1900acf996","55f036938eeefc23001ea5de","55f036a38563861700a33767","55f036c08563861700a33769","55f036d02911b72100482cd7","55f036e92911b72100482cd9","55f036fa8563861700a3376b","55f0370ee507711900e58c69","55f0371df6101b1900c70700","55f0374f2911b72100482cdb","55f0375e2911b72100482cdc","560eb0f659cb8d0d0015cd52","560eb25239fad419002ae1e0","561fb64d4d67490d00804b2a","562b9f775a39cd0d009aff22","562ba0505a39cd0d009aff23","562ba149d56bc30d00f0cb18","562ba595f68a5f0d007b1f3b","562ba78fd56bc30d00f0cb1b","562ba8b95a39cd0d009aff27","562baadf6562140d001501d2","562bab37f68a5f0d007b1f3d","562bc1bf9ebc950d000f7523","562bc99ced4bea0d00c11dfa","562bd29c1b98640d00714520","562bd5875a39cd0d009aff60","562bdfabff2da50d002c0aaf","562be0bd5a39cd0d009aff75","57a0b476d8313e1900454439","5b19051beece890003020163","5b34ded01cb20f000391ad6d","5b3a325acffe770003fd29e5","5b3c737a7f7b890003365501","5b3c929b367036000391b11e","5b7c1e210dc2e20003871521"],"is_deprecated":false,"is_hidden":false,"is_beta":false,"is_stable":true,"codename":"","version_clean":"2.0.0","version":"2"},"category":{"_id":"5b34ded01cb20f000391ad6d","project":"55dd9f2e0efd5821000d54d9","version":"55dd9f4dab0e4d210045aae9","__v":0,"sync":{"url":"","isSync":false},"reference":false,"createdAt":"2018-06-28T13:12:48.898Z","from_sync":false,"order":2,"slug":"push-notifications","title":"Push notifications"},"user":"5a251846c297dc0012e531cd","githubsync":"","__v":0,"parentDoc":null,"updates":[],"next":{"pages":[],"description":""},"createdAt":"2018-07-17T11:07:40.065Z","link_external":false,"link_url":"","sync_unique":"","hidden":false,"api":{"results":{"codes":[]},"settings":"","auth":"required","params":[],"url":""},"isReference":false,"order":4,"body":"[block:html]\n{\n  \"html\": \"<div id=\\\"userMap\\\">\\n<div class=\\\"content\\\"><a href=\\\"https://developer.dotmailer.com/v2/docs/creating-a-push-notification-profile\\\"><div class=\\\"box box1\\\">Create a push notification profile in dotmailer</div></a></div>\\n<div class=\\\"arrow\\\">→</div>\\n<div class=\\\"content\\\"><a href=\\\"https://developer.dotmailer.com/v2/docs/creating-a-json-web-token\\\"><div class=\\\"box box2\\\">Create a class or function that generates a JSON Web Token</div></a></div>\\n<div class=\\\"arrow\\\">→</div>\\n<div class=\\\"content\\\"><a href=\\\"https://developer.dotmailer.com/v2/docs/setting-up-push-notifications#section-mobile-sdk-options\\\"><div class=\\\"box box3 active\\\">Use one of our mobile SDKs in your app</div></a></div>\\n<div class=\\\"clearfix\\\"></div></div>\\n\\n<style>\\n  .box {\\n    padding: 10px;\\n    border: 2px solid #000;\\n    width: 120px;\\n    height: 120px;\\n    background-color: #EAEAEA;\\n    hyphens: auto;\\n    float: left;\\n    font-size: 12px;\\n}\\n\\n.box:hover {\\n    background-color: #82bc42;\\n}\\n\\n.box.active {\\n    background-color: #82bc42;\\n}\\n\\n#userMap {\\n    overflow-x: auto;\\n    overflow-y: auto;\\n    padding: 20px;\\n    min-width: 770px;\\n}\\n\\n#userMap a:hover {\\n    text-decoration: none;\\n  }\\n\\ndiv.arrow {\\n    max-width: 50px;\\n    margin-left: 15px;\\n    margin-right: 15px;\\n    font-size: 50px;\\n}\\n\\n\\n#userMap div.arrow, #userMap div.content {\\n    float: left;\\n}\\n\\n.clearfix {\\n    clear: both;\\n}\\n\\n\\n#userMap div.arrow {\\n    position: relative;\\n    top: 45px;\\n}\\n\\n.box1 {\\n    margin-left:0px;\\n}\\n\\ndiv.box.box1 {\\n    margin-left: -20px;\\n}\\n\\n</style>\"\n}\n[/block]\nOur iOS SDK uses the [Apple Push Notification Service (APNs)](https://developer.apple.com/library/archive/documentation/NetworkingInternet/Conceptual/RemoteNotificationsPG/APNSOverview.html#//apple_ref/doc/uid/TP40008194-CH8-SW1) to send push notifications to your contacts.\n\nTo set up push notifications for native iOS apps, complete the following tasks:\n\n1. [Install the iOS SDK](#section-installing-the-ios-sdk)\n2. [Configure the iOS SDK](#section-configuring-the-ios-sdk)\n3. [Initialise the iOS SDK](#section-initialising-the-ios-sdk)\n4. [Add an email address the the iOS app user's profile](#section-adding-an-email-address-to-the-ios-app-user-s-profile)\n\n# Installing the iOS SDK\n\nTo add the iOS SDK to your Xcode project with CocoaPods, do the following: \n\n1. Add the iOS SDK to your podfile\n[block:code]\n{\n  \"codes\": [\n    {\n      \"code\": \"use_frameworks!\\n\\npod 'ComapiFoundation'\",\n      \"language\": \"swift\",\n      \"name\": \"CocoaPods\"\n    }\n  ]\n}\n[/block]\n2. Install the iOS SDK\n[block:code]\n{\n  \"codes\": [\n    {\n      \"code\": \"$ pod install\",\n      \"language\": \"shell\"\n    }\n  ]\n}\n[/block]\n3. Import the iOS SDK in your Swift file\n[block:code]\n{\n  \"codes\": [\n    {\n      \"code\": \"import ComapiFoundation\",\n      \"language\": \"swift\"\n    }\n  ]\n}\n[/block]\n# Configuring the iOS SDK\n\nBefore you can configure the iOS SDK, you need the following:\n\n* The value of the [API space ID field in dotmailer](doc:creating-a-push-notification-profile#section-finding-your-api-space-id)\n* A class that [creates a JWT token](https://developer.dotmailer.com/v2/docs/creating-a-json-web-token#section-ios-jwt-code-sample)\n* Your app must be set up so that it [asks the user for permission to send push notifications](https://developer.apple.com/documentation/usernotifications/asking_permission_to_use_notifications).\n\nTo configure the iOS SDK:\n\n1. Create a new instance of the `ComapiConfig` class and store it in a variable\n\n2. As the first argument of the `ComapiConfig` instance, pass your API Space ID\n\n3. As the second argument of the `ComapiConfig` instance, pass an instance of [a class that creates a JWT token](#section-ios-jwt-code-sample)\n[block:code]\n{\n  \"codes\": [\n    {\n      \"code\": \"let config = ComapiConfig(apiSpaceId: \\\"<API_SPACE_ID>\\\", authenticationDelegate: ChallengeHandler())\",\n      \"language\": \"swift\"\n    }\n  ]\n}\n[/block]\n## Configuring your app to ask users' permission to send them push notifications\n\nTo receive push notifications, app users must give their permission.\n\nCall the `application(_:didRegisterForRemoteNotificationsWithDeviceToken:)` [method](https://developer.apple.com/documentation/uikit/uiapplicationdelegate/1622958-application?language=swift) to get the `deviceToken` string and pass it to the `setPushToken()` method on the `ComapiClient` object.\n[block:code]\n{\n  \"codes\": [\n    {\n      \"code\": \"func application(_ application: UIApplication,\\n                     didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {\\n        if let tokenString = String(data: deviceToken, encoding: .utf8) {\\n        \\t//Comapi.shared() gets the ComapiClient object\\n            try? Comapi.shared().setPushToken(tokenString, completion: {_ in})\\n        \\n        }\\n                /*Put your custom code here*/\\n\\n}\",\n      \"language\": \"swift\"\n    }\n  ]\n}\n[/block]\n## Displaying push notifications when the app is in the foreground\n\nPush notifications are displayed only while the app is in the background. These notification are sent to the notification center and launch your app when users tap them.\n\nIf you want to display the push notification message while the app is in the foreground, do one of the following, depending on the iOS version that your app is running on:\n\n**For iOS 9** \n[block:code]\n{\n  \"codes\": [\n    {\n      \"code\": \"func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable : Any]) {\\n  if application.applicationState == .active {\\n    // Handle the notification here\\n  }\\n}\",\n      \"language\": \"swift\"\n    }\n  ]\n}\n[/block]\n**For iOS 10 and above** \n[block:code]\n{\n  \"codes\": [\n    {\n      \"code\": \"func userNotificationCenter(_ center: UNUserNotificationCenter,\\n                                willPresent notification: UNNotification,\\n                                withCompletionHandler completionHandler: :::at:::escaping (UNNotificationPresentationOptions) -> Void) {\\n  completionHandler(.alert)\\n}\",\n      \"language\": \"swift\"\n    }\n  ]\n}\n[/block]\n## Configuring logs\n\nYou can set internal file logs and console logs to the following levels:\n\n* `verbose`\n* `debug`\n* `info`\n* `warning`\n* `error`\n[block:code]\n{\n  \"codes\": [\n    {\n      \"code\": \"Log.consoleDestination.minimumLevel = .error\\nLog.fileDestination.minimumLevel = .info\",\n      \"language\": \"swift\"\n    }\n  ]\n}\n[/block]\n# Initialising the iOS SDK\n\nAfter you've configured the SDK, pass the variable that contains the `ComapiConfig` object to one of the following initialisation methods. These methods return a `ComapiClient` object that you can use to access the `session` service and the `profile` service, which are used to create and update the user's profile.\n\n* The `Comapi.initialiseSharedInstance()` method: When you use this method, the SDK stores the  'ComapiClient' object, and you can access it at any time by calling the `Comapi.getShared()` method.\n* The `Comapi.initialise()` method:  When you use this method, you need to store the `ComapiClient` object yourself. The `getShared()` method is not available when you use this method.\n[block:code]\n{\n  \"codes\": [\n    {\n      \"code\": \"let client = Comapi.initialise(config: config)\",\n      \"language\": \"swift\"\n    }\n  ]\n}\n[/block]\n# Adding an email address to the iOS app user's profile\n\nPush notifications can be sent from dotmailer only to users who have a profile that contains an email address.\n\nTo create a profile for the user, a session must be started. A session is started automatically after initialisation, but you can also start it explicitly by calling the `client.services.session.startSession()` method.\n\nWhen a session is started, the JWT token is used to create the user's profile ID ('profileId' string). This profile ID remains the same until a session is stopped.\n\nWhen a session is stopped and started again, a new JWT token is created and used to create a new profile ID.\n\nA session is stopped in any of the following circumstances:\n\n* The user uninstalls the app, and then reinstalls it\n* The user clears all of the app's data\n\nYou can also stop a session by calling the `client.services.session.endSession()` method.\n[block:callout]\n{\n  \"type\": \"warning\",\n  \"title\": \"Ask users to enter their email address\",\n  \"body\": \"You should ask users if they'd like to receive push notifications from you and prompt them to enter their email address.\"\n}\n[/block]\n\n[block:code]\n{\n  \"codes\": [\n    {\n      \"code\": \"client.services.profile.updateCurrentProfile([\\\"email\\\": \\\"exampleappuser1@gmail.com\\\"]) { result in\\n  // completion handler\\n}\",\n      \"language\": \"swift\"\n    }\n  ]\n}\n[/block]\nNow, when a user launches your app, the user's profile data is sent to dotmailer and (if that profile contains an email address that belongs to one of your contacts) that contact can now receive push notifications from dotmailer :tada: .\n[block:callout]\n{\n  \"type\": \"success\",\n  \"body\": \"[Send a push notification to your app](https://support.dotmailer.com/hc/en-gb/articles/360001827870) from the program builder in dotmailer.\",\n  \"title\": \"Next steps\"\n}\n[/block]","excerpt":"A tutorial for adding the iOS SDK code to your app to allow your app users to receive push notifications from your dotmailer account.","slug":"ios-sdk","type":"basic","title":"Using the iOS SDK"}

Using the iOS SDK

A tutorial for adding the iOS SDK code to your app to allow your app users to receive push notifications from your dotmailer account.

[block:html] { "html": "<div id=\"userMap\">\n<div class=\"content\"><a href=\"https://developer.dotmailer.com/v2/docs/creating-a-push-notification-profile\"><div class=\"box box1\">Create a push notification profile in dotmailer</div></a></div>\n<div class=\"arrow\">→</div>\n<div class=\"content\"><a href=\"https://developer.dotmailer.com/v2/docs/creating-a-json-web-token\"><div class=\"box box2\">Create a class or function that generates a JSON Web Token</div></a></div>\n<div class=\"arrow\">→</div>\n<div class=\"content\"><a href=\"https://developer.dotmailer.com/v2/docs/setting-up-push-notifications#section-mobile-sdk-options\"><div class=\"box box3 active\">Use one of our mobile SDKs in your app</div></a></div>\n<div class=\"clearfix\"></div></div>\n\n<style>\n .box {\n padding: 10px;\n border: 2px solid #000;\n width: 120px;\n height: 120px;\n background-color: #EAEAEA;\n hyphens: auto;\n float: left;\n font-size: 12px;\n}\n\n.box:hover {\n background-color: #82bc42;\n}\n\n.box.active {\n background-color: #82bc42;\n}\n\n#userMap {\n overflow-x: auto;\n overflow-y: auto;\n padding: 20px;\n min-width: 770px;\n}\n\n#userMap a:hover {\n text-decoration: none;\n }\n\ndiv.arrow {\n max-width: 50px;\n margin-left: 15px;\n margin-right: 15px;\n font-size: 50px;\n}\n\n\n#userMap div.arrow, #userMap div.content {\n float: left;\n}\n\n.clearfix {\n clear: both;\n}\n\n\n#userMap div.arrow {\n position: relative;\n top: 45px;\n}\n\n.box1 {\n margin-left:0px;\n}\n\ndiv.box.box1 {\n margin-left: -20px;\n}\n\n</style>" } [/block] Our iOS SDK uses the [Apple Push Notification Service (APNs)](https://developer.apple.com/library/archive/documentation/NetworkingInternet/Conceptual/RemoteNotificationsPG/APNSOverview.html#//apple_ref/doc/uid/TP40008194-CH8-SW1) to send push notifications to your contacts. To set up push notifications for native iOS apps, complete the following tasks: 1. [Install the iOS SDK](#section-installing-the-ios-sdk) 2. [Configure the iOS SDK](#section-configuring-the-ios-sdk) 3. [Initialise the iOS SDK](#section-initialising-the-ios-sdk) 4. [Add an email address the the iOS app user's profile](#section-adding-an-email-address-to-the-ios-app-user-s-profile) # Installing the iOS SDK To add the iOS SDK to your Xcode project with CocoaPods, do the following: 1. Add the iOS SDK to your podfile [block:code] { "codes": [ { "code": "use_frameworks!\n\npod 'ComapiFoundation'", "language": "swift", "name": "CocoaPods" } ] } [/block] 2. Install the iOS SDK [block:code] { "codes": [ { "code": "$ pod install", "language": "shell" } ] } [/block] 3. Import the iOS SDK in your Swift file [block:code] { "codes": [ { "code": "import ComapiFoundation", "language": "swift" } ] } [/block] # Configuring the iOS SDK Before you can configure the iOS SDK, you need the following: * The value of the [API space ID field in dotmailer](doc:creating-a-push-notification-profile#section-finding-your-api-space-id) * A class that [creates a JWT token](https://developer.dotmailer.com/v2/docs/creating-a-json-web-token#section-ios-jwt-code-sample) * Your app must be set up so that it [asks the user for permission to send push notifications](https://developer.apple.com/documentation/usernotifications/asking_permission_to_use_notifications). To configure the iOS SDK: 1. Create a new instance of the `ComapiConfig` class and store it in a variable 2. As the first argument of the `ComapiConfig` instance, pass your API Space ID 3. As the second argument of the `ComapiConfig` instance, pass an instance of [a class that creates a JWT token](#section-ios-jwt-code-sample) [block:code] { "codes": [ { "code": "let config = ComapiConfig(apiSpaceId: \"<API_SPACE_ID>\", authenticationDelegate: ChallengeHandler())", "language": "swift" } ] } [/block] ## Configuring your app to ask users' permission to send them push notifications To receive push notifications, app users must give their permission. Call the `application(_:didRegisterForRemoteNotificationsWithDeviceToken:)` [method](https://developer.apple.com/documentation/uikit/uiapplicationdelegate/1622958-application?language=swift) to get the `deviceToken` string and pass it to the `setPushToken()` method on the `ComapiClient` object. [block:code] { "codes": [ { "code": "func application(_ application: UIApplication,\n didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {\n if let tokenString = String(data: deviceToken, encoding: .utf8) {\n \t//Comapi.shared() gets the ComapiClient object\n try? Comapi.shared().setPushToken(tokenString, completion: {_ in})\n \n }\n /*Put your custom code here*/\n\n}", "language": "swift" } ] } [/block] ## Displaying push notifications when the app is in the foreground Push notifications are displayed only while the app is in the background. These notification are sent to the notification center and launch your app when users tap them. If you want to display the push notification message while the app is in the foreground, do one of the following, depending on the iOS version that your app is running on: **For iOS 9** [block:code] { "codes": [ { "code": "func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable : Any]) {\n if application.applicationState == .active {\n // Handle the notification here\n }\n}", "language": "swift" } ] } [/block] **For iOS 10 and above** [block:code] { "codes": [ { "code": "func userNotificationCenter(_ center: UNUserNotificationCenter,\n willPresent notification: UNNotification,\n withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {\n completionHandler(.alert)\n}", "language": "swift" } ] } [/block] ## Configuring logs You can set internal file logs and console logs to the following levels: * `verbose` * `debug` * `info` * `warning` * `error` [block:code] { "codes": [ { "code": "Log.consoleDestination.minimumLevel = .error\nLog.fileDestination.minimumLevel = .info", "language": "swift" } ] } [/block] # Initialising the iOS SDK After you've configured the SDK, pass the variable that contains the `ComapiConfig` object to one of the following initialisation methods. These methods return a `ComapiClient` object that you can use to access the `session` service and the `profile` service, which are used to create and update the user's profile. * The `Comapi.initialiseSharedInstance()` method: When you use this method, the SDK stores the 'ComapiClient' object, and you can access it at any time by calling the `Comapi.getShared()` method. * The `Comapi.initialise()` method: When you use this method, you need to store the `ComapiClient` object yourself. The `getShared()` method is not available when you use this method. [block:code] { "codes": [ { "code": "let client = Comapi.initialise(config: config)", "language": "swift" } ] } [/block] # Adding an email address to the iOS app user's profile Push notifications can be sent from dotmailer only to users who have a profile that contains an email address. To create a profile for the user, a session must be started. A session is started automatically after initialisation, but you can also start it explicitly by calling the `client.services.session.startSession()` method. When a session is started, the JWT token is used to create the user's profile ID ('profileId' string). This profile ID remains the same until a session is stopped. When a session is stopped and started again, a new JWT token is created and used to create a new profile ID. A session is stopped in any of the following circumstances: * The user uninstalls the app, and then reinstalls it * The user clears all of the app's data You can also stop a session by calling the `client.services.session.endSession()` method. [block:callout] { "type": "warning", "title": "Ask users to enter their email address", "body": "You should ask users if they'd like to receive push notifications from you and prompt them to enter their email address." } [/block] [block:code] { "codes": [ { "code": "client.services.profile.updateCurrentProfile([\"email\": \"exampleappuser1@gmail.com\"]) { result in\n // completion handler\n}", "language": "swift" } ] } [/block] Now, when a user launches your app, the user's profile data is sent to dotmailer and (if that profile contains an email address that belongs to one of your contacts) that contact can now receive push notifications from dotmailer :tada: . [block:callout] { "type": "success", "body": "[Send a push notification to your app](https://support.dotmailer.com/hc/en-gb/articles/360001827870) from the program builder in dotmailer.", "title": "Next steps" } [/block]