This article guides you through the process of enabling push notifications for the Chat SDK in your iOS app.

Note: This guide does not discuss provisioning profiles. Please ensure you have your provisioning configured before starting this guide if you are planning to create a distribution certificate. Development/sandbox certificates can be tested with an Xcode managed profile.

1. Enabling push notifications with Apple and generating the .p12 certificate

  1. Sign into the Identifiers section of the Apple Developer Member Center and select your app.

  2. Under Capabilities, enable Push Notifications and then click Configure.

  3. Under Production SSL Certificate, select Create Certificate.

  4. Follow the instructions in Create a certificate signing request on the Apple Developer Centre to generate a certificate signing request using Keychain Access.

  5. After the Apple Push Services Certificate is generated, download and double-click it to open it in Keychain Access.

  6. Right-click on the certificate you created and select Export "Apple Developer IOS Push Services...".

  7. Save the .p12 file to your computer. Leave the password empty.

  8. Save the .cer file to your computer. Leave the password empty.

2. Generating the .pem file

Generate the .pem file for your .p12 file using the OpenSSL pkcs12 command. See pcks12 on www.openssl.org. You can leave the Import Password empty.

$ openssl pkcs12 -clcerts -nodes -in your.p12 -out your.pem

Your .pem file should contain the certificate and private key sections. It should also contain Bag Attributes information about your bundle identifier, company name, and other information.

Example .pem file:

Bag Attributes    friendlyName: Apple Push Services: your.bundle.identifier    localKeyID: <key data>subject=/UID=your.bundle.identifier/CN=Apple Push Services: your.bundle.identifier/OU=0000000/O=Your Company/C=Country Codeissuer=/C=US/O=Apple Inc./OU=Apple Worldwide Developer Relations/CN=Apple Worldwide Developer Relations Certification Authority-----BEGIN CERTIFICATE-----<certificate data>-----END CERTIFICATE-----Bag Attributes    friendlyName: Developer name    localKeyID: <key data>Key Attributes: <No Attributes>-----BEGIN PRIVATE KEY-----<private key data>-----END PRIVATE KEY-----

3. Testing your .pem file

You can test your .pem file by connecting to Apple's Production APNS server.

$ openssl s_client -connect gateway.push.apple.com:2195 -cert your.pem -key your.pem

If your .pem was correctly generated, an SSL session will be established with the Apple APNS server and you'll receive the return code 0 == ok.

If you receive a different code, make sure to revisit Step 2 above, or follow the instructions in the response.

Example response from Apple APNS server:

New, TLSv1/SSLv3, Cipher is DES-CBC3-SHAServer public key is 2048 bitSecure Renegotiation IS supportedCompression: NONEExpansion: NONENo ALPN negotiatedSSL-Session:    Protocol  : TLSv1.2    Cipher    : DES-CBC3-SHA    Session-ID:    Session-ID-ctx:    Master-Key: XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX    Start Time: 1563378474    Timeout   : 7200 (sec)    Verify return code: 0 (ok)---

4. Uploading your .pem file to the Chat dashboard

If you're not a Chat admin, ask one to complete this step for you.

To upload your .pem file to the Chat dashboard

  1. In the Chat dashboard, go to Settings > Account > API & SDKs.

  2. Select your dashboard app and click Select PEM file for iOS

  3. Upload your .pem file and save the changes.

  4. Additionally you can enable the For APNS Sandbox checkbox to leverage the sandbox APNs environment.

It's good practice to store your .pem file in a safe place in case you need to use it later.

Note: The complete guide to enable the push notifications for your app in your Chat Dashboard can be found here here.

5. Set up push notifications for Chat SDK in your app

To set up push notifications in your app

  1. Turn on Push Notifications in your targets Capabilities tab.

  2. Turn on Remote Notifications in the Background Modes in your target's Capabilities tab.

    See the Apple documentation to learn more about remote notifications and how they work in background mode.

  3. Set distribution APS Environment in the app's .entitlements file to allow the app to be signed with a production push certificate during deployment.

  4. Register for Push Notifications using UNUserNotificationCenter in your AppDelegate only for the device. See Setting up in-app push notifications for Chat SDK below to implement UNUserNotificationCenter.

    Swift

    import UserNotifications  #if !TARGET_IPHONE_SIMULATORlet notificationCenter = UNUserNotificationCenter.current()notificationCenter.delegate = selfnotificationCenter.requestAuthorization(options: [.alert, .sound, .badge]) { granted, _ in    guard granted else { return }
        DispatchQueue.main.async {       UIApplication.shared.registerForRemoteNotifications()    }}#endif

    Objective-C

    #import <UserNotifications/UserNotifications.h>  @interface AppDelegate : UIResponder <UIApplicationDelegate, UNUserNotificationCenterDelegate>#if !TARGET_IPHONE_SIMULATORUNUserNotificationCenter *center = [UNUserNotificationCenter currentNotificationCenter];center.delegate = self;[center requestAuthorizationWithOptions:(UNAuthorizationOptionSound | UNAuthorizationOptionAlert | UNAuthorizationOptionBadge)    completionHandler:^(BOOL granted, NSError * _Nullable error){   if (!error){       [[UIApplication sharedApplication] registerForRemoteNotifications];   }}];#endif
  5. Override the func application (_application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) function in your AppDelegate.

    Chat v2 - Swift

    import ChatProvidersSDK  func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {   Chat.registerPushToken(deviceToken)}

    Chat v2 - Objective-C

    @import ChatProvidersSDK;  - (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken {    [ZDKChat registerPushToken:deviceToken];}

    Chat v1 - Swift

    import Chat  func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {    ZDCChat.setPushToken(deviceToken)}

    Chat v1 - Objective-C

    #import <ZDCChat/ZDCChat.h>  - (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken {    [ZDCChat setPushToken:deviceToken];}
  6. Pass the received push notification to the Chat SDK.

    Chat v2 - Swift

    import ChatProvidersSDK   func userNotificationCenter(_ center: UNUserNotificationCenter,   didReceive response: UNNotificationResponse,   withCompletionHandler completionHandler: @escaping () -> Void) {      let userInfo = response.notification.request.content.userInfo      let application = UIApplication.shared      Chat.didReceiveRemoteNotification(userInfo, in: application)      completionHandler()   }

    Chat v2 - Objective-C

    @import ChatProvidersSDK;  - (void)userNotificationCenter:(UNUserNotificationCenter *)center didReceiveNotificationResponse:(UNNotificationResponse *)response withCompletionHandler:(void(^)())completionHandler{      [ZDKChat didReceiveRemoteNotification:userInfo in:application];      completionHandler();  }

    Chat v1 - Swift

    import ZDCChat  func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable : Any], fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) {    ZDCChat.didReceiveRemoteNotification(userInfo)    completionHandler(.noData)}

    Chat v1 - Objective-C

    #import <ZDCChat/ZDCChat.h>  - (void) application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo fetchCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler {    [ZDCChat didReceiveRemoteNotification:userInfo];    completionHandler(UIBackgroundFetchResultNoData);}

6. Setting up in-app push notifications for Chat SDK

Allow the notifications to be shown in your app by implementing the UNUserNotificationCenterDelegate method.

Swift

import UserNotifications
func userNotificationCenter(_ center: UNUserNotificationCenter,                            willPresent notification: UNNotification,                            withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {    completionHandler([.alert, .sound, .badge])}

Objective-C

#import <UserNotifications/UserNotifications.h>// In AppDelegate.h conform AppDelegate to UNUserNotificationCenterDelegate@interface AppDelegate : UIResponder <UIApplicationDelegate, UNUserNotificationCenterDelegate>- (void)userNotificationCenter:(UNUserNotificationCenter *)center           willPresentNotification:(UNNotification *)notification         withCompletionHandler:(void (^)(UNNotificationPresentationOptions options))completionHandler {            completionHandler(UNNotificationPresentationOptionAlert | UNNotificationPresentationOptionSound | UNNotificationPresentationOptionBadge);}