IBM Cloud Docs
Create and send push notifications to iOS mobile using Event Notifications

Create and send push notifications to iOS mobile using Event Notifications

Create an Event Notifications service, add a push destination for Apple Push Notification service (APNs), and send messages to iOS devices.

What is Event Notifications?

Event Notifications is an event notification routing service that notifies you of critical events that occur in your IBM Cloud account or triggers automated actions by using webhooks. You can filter and route event notifications from IBM Cloud services like Availability Monitoring, to email, SMS, push notifications (FCM or APNs), and webhooks.

How do clients use iOS Push Notifications?

The following diagram shows you how clients use iOS Push Notifications.

How clients use push notifications
Figure 1. How clients use push notifications

Objectives

This tutorial shows you how to send push notifications as follows:

  • Create a mobile app with Event Notifications.
  • Get APNs credentials.
  • Download the code and complete the notifications setup.
  • Configure and send iOS Push Notifications to a mobile device.

Before you begin

You must have the following prerequisites in place:

  • An IBM Cloud account. If you do not have one, create an IBM Cloud account.
  • An Event Notifications instance.
  • An IAM API key to allow the SDK to access your account. Create one here.
  • Xcode 9.3+
  • Swift 4.2+
  • iOS 10.0+

Create an Event Notifications service instance

  • Log in to your IBM Cloud account.
  • In the IBM Cloud catalog, search Event Notifications > Event Notifications.
  • Select a Region from the list of supported regions and select a pricing plan.
  • Provide a Service name.
  • Select a resource group.
  • Accept the licensing agreements and terms by clicking the checkbox.
  • Click Create.

Get APNs credentials

For iOS devices and applications, Apple Push Notification Service (APNs) allows application developers to send remote notifications from Event Notifications service instance on IBM Cloud (the provider) to iOS devices and applications. Messages are sent to a target application on the device.

You need to obtain and configure your APNs credentials. The APNs certificates are securely managed by Event Notifications service and used to connect to APNs server as a provider.

Registering an App ID

The App ID (the bundle identifier) is a unique identifier that identifies a specific application. Each application requires an App ID. Services like the Push Notifications service are configured to the App ID.

  • Go to the Apple developer portal and select Certificates, Identifiers & Profiles.

    Certificates, Identifiers & Profiles
    Figure 2. Certificates, Identifiers & Profiles

  • Go to Identifiers > Add identifier button.

    Identifier button
    Figure 3. Identifier Button

  • Click add a new Identifier button.

    Add new Identifier button
    Figure 4. Add new Identifier button

  • Select the App IDs option.

    App IDs option
    Figure 5. App IDs option

  • Select a type and click Continue.

    App ID type
    Figure 6. App ID type

  • Provide a string for the App ID Prefix. Provide the App name in the Description field. For example, Event Notifications iOS application.

  • For the Bundle ID, choose Explicit and provide a Bundle ID value. It is recommended that you provide a reverse domain-name style string. For example, com.ibm.cloud.en.app.

    Create new App ID details
    Figure 7. Create new App ID details

  • Select the Push Notifications check-box from the Capabilities and click Continue.

    Enable Push Notifications
    Figure 8. Enable Push Notifications

  • Go through your settings and click Register > Done.

Your App ID is now registered.

App ID
Figure 9. Newly created App ID

Create a development and distribution APNs SSL certificate

Before you obtain an APNs certificate, you must first generate a certificate signing request (CSR) and submit it to Apple, the certificate authority (CA). The CSR contains information that identifies your company and your public and private key that you use to sign for your Apple push notifications. Then, generate the SSL certificate on the iOS Developer Portal. The certificate, along with its public and private key, is stored in Keychain Access.

You can use APNs in two modes:

  • Sandbox mode for development and testing.
  • Production mode when distributing applications through the App Store (or other enterprise distribution mechanisms).

You must obtain separate certificates for your development and distribution environments. The certificates are associated with an App ID for the app that is the recipient of remote notifications. For production, you can create up to two certificates. IBM Cloud uses the certificates to establish an SSL connection with APNs.

Create an APNs p12 certificate

  • Go to the Apple developer portal and select Certificates, Identifiers & Profiles.

    Certificates, Identifiers & Profiles
    Figure 10. Certificates, Identifiers & Profiles

  • In the Identifiers area, select your App ID.

    Identifiers tab
    Figure 11. Identifiers tab

  • Select the Push Notifications check-box OR select the Edit option.

    Push Notifications check-box
    Figure 12. Push Notifications check-box

    • On Development SSL certificate pane, click Create Certificate...
    • On Production SSL certificate pane, click Create Certificate...

    Certificate type
    Figure 13. Certificate type

  • Use Keychain Access application on your Mac to create a Certificate Signing Request (CSR).

  • From the menu, select Keychain Access > Certificate Assistant > Request a Certificate From a Certificate Authority….

    Request new certificate
    Figure 14. Request new certificate type

  • In Certificate Information, enter the email address that is associated with your App Developer account and a common name. Give a meaningful name that helps you identify whether it is a certificate for development (sandbox) or distribution (production); for example, sandbox-apns-certificate or production-apns-certificate.

  • Select Saved to disk to download the .certSigningRequest file to your Mac, then click Continue.

    Certificate details
    Figure 15. Certificate details

  • In the Save As menu option, name the .certSigningRequest file, select the location where the file must be saved, and click Save.

    Save CSR file
    Figure 16. Save CSR file

  • Click Done. You now have a CSR.

    CSR created
    Figure 17. CSR created

  • Go back to the Apple developer portal, for the Upload CSR file option, click Choose File, and select file CertificateSigningRequest.certSigningRequest. Click Continue.

    Upload CSR file
    Figure 18. Upload CSR file

  • Click Download. The aps_development.cer file is downloaded.

    Download certificate
    Figure 19. Download certificate

  • Locate your newly installed certificate. Double-click the certificate to install it into the Keychain Access.

  • On your Mac, go to Keychain Access > My Certificates.

  • Select the certificate and private key, and then select Export to convert the certificate into the personal information exchange format (.p12 format).

    Export certificate
    Figure 20. Export certificate

  • In the Save As field, provide the certificate a meaningful name. For example, sandbox-apns.p12 or production-apns.p12, then click Save.

    Save certificate
    Figure 21. Save certificate

  • In the Enter a password field, enter a password to protect the exported items, then click OK. You can use this password to configure your APNs settings on the Event Notifications service console.

    Protect certificate
    Figure 22. Protect certificate

  • The Key Access app prompts you to export your key from the Keychain screen. Enter your administrative password for your Mac to allow your system to export these items, and then select the Always Allow option. A .p12 certificate is generated on your selected location.

Create an APNs p8 token

  • Go to the Apple developer portal and select Certificates, Identifiers & Profiles.

    Certificates, Identifiers & Profiles
    Figure 23. Certificates, Identifiers & Profiles

  • Go to Keys tab.

    Keys tab
    Figure 24. Keys tab

  • Enter Key Name and enable APNs, click continue.

    P8 token details
    Figure 25. P8 token details

  • Click Register.

    Register p8 token
    Figure 26. Register p8 token

  • Make sure to download the Keys in new redirected page after registration as it is a one time activity.

KeyID is visible as part of the file and displayed in the UI, this KeyID is used for registering APNS certificate. TeamID is provided by apple for the developer account, can be seen next to the Team Name. TeamID is used for registering APNS certificate. BundleID can be registered same as P12 certificate.

Add a generic API source

Take the following steps:

  • Go to the Sources section of the Event Notifications dashboard.
  • Click Add and select an API Source.
  • Type a name and an optional description and click Add.

Create a Event Notifications destination

Click Destinations in the Event Notifications console and add the following destination details:

  • Name: add a name for the Destination.
  • Description: add an optional description for the destination.
  • Type: select iOS Push Notifications type from the dropdown list.
  • Select a destination plan: Pre-production destination or Production destination.
    • Pre-production destination - select this destination as low-cost push destination, for your development and test environments.
    • Production destination - use the full capability of this destination. Unlimited devices and outbound messages allowed.
  • Update the iOS Push Credentials with the details based on Authentication Type and select Environment.
    • if certificate type is p8, upload .p8 file and provide KeyID, TeamID, and BundleID.
    • if certificate type is p12, upload p12 certificate and provide certificate password.
  • Click Add.

Create an Event Notifications topic

Select Topics in the Event Notifications console and click Create. Enter the following topic details:

  • Name: enter a name for the topic.
  • Description: add an optional description for the topic.
  • Source: select a source from the dropdown list.
  • Event type: select event type from the dropdown list.
  • Event sub type select event sub type from the event sub type dropdown list.
  • Severity: select severity from the severity dropdown list.
  • Advanced conditions: write your own custom conditions, which must follow jsonpath specifications.

Create an Event Notifications subscription

Click Subscriptions in the Event Notifications console. Enter the following subscription details:

  • Click Create to display subscription wizard.
  • Complete the following subscription details:
    • Subscription name: name of the subscription.
    • Subscription description: add an optional description.
  • Under the Subscribe to a topic section, select a topic from the drop-down list and select a destination from the destination drop-down list.
  • Destination type: select type under Destination and click Add.

Set up Event Notifications IOS SDK

The iOS SDK enables iOS apps to receive push notifications. Complete the following steps to install Event Notifications iOS SDK, initialize the SDK, and register for notifications for your iOS app.

Installation

The current version of this SDK is: 0.0.1

To use the Event Notifications iOS destination SDK, define a dependency that contains the artifact coordinates (group ID, artifact ID, and version) for the service, like this:

CocoaPods

use_frameworks!

target 'MyApp' do
   pod 'ENPushDestination', '~> 0.0.1'
end

Carthage

To install ENPushDestination using Carthage, add the following to your Cartfile.

github "IBM/event-notifications-destination-ios-sdk" ~> 0.0.1

Then, run the following command to build the dependencies and frameworks:

carthage update --platform iOS

Swift Package Manager

Add the following to your Package.swift file to identify ENPushDestination as a dependency. The package manager clones ENPushDestination when you build your project with swift build.

dependencies: [
   .package(url: "https://github.com/IBM/event-notifications-destination-ios-sdk", from: "0.0.1")
]

Installation - Initialize SDK

Complete the following steps to enable iOS applications to receive notifications.

  1. Add the import statements in your .swift file.

    import ENPushDestination
    
  2. Initialize the ENPushDestination SDK

    let instanceGUID = "<instance_guid>>";
    let destinationID = "<instance_destination_id>";
    let apiKey = "<instance_apikey>";
    
    let enPush = ENPush.sharedInstance
    enPush.setCloudRegion(region: .usSouth)
    enPush.initialize(instanceGUID, destinationID, apiKey)
    
    • region: Region of the Event Notifications instance. For example, Region.usSouth.

Register for notifications

Use the ENPush.registerDevice() API to register the device with iOS destination in Event Notifications service.

The following options are supported:

  • Register without userId:

    /**Register iOS devices*/
    enPush.registerWithDeviceToken(deviceToken: "<apns-device-token>") { response, statusCode, error in
       print(response?.id ?? "")
    }
    
  • Register with UserId. For userId based notification, the register method accepts one more parameter - userId.

    /**Register iOS devices*/
    enPush.registerWithDeviceToken(deviceToken: "<apns-device-token>", withUserId: "userId") { response, statusCode, error in
    
       print(response?.id ?? "")
    
    }
    

    The userId is used to pass the unique userId value for registering for Event Notifications.

Unregistering from notifications

Use the following code snippets to unregister from Event Notifications.

enPush.unregisterDevice { response, statusCode, error in
   /**.....*/
}

To unregister from the UserId based registration, you must call the registration method. See the Register without userId option in Register for notifications.

Event Notifications destination tags subscriptions

Subscribe to tags

The subscribe API subscribes the device for a given tag. After the device is subscribed to a particular tag, the device can receive notifications that are sent for that tag.

Add the following code snippet to your iOS mobile application to subscribe to a list of tags.

// Subscribe to the given tag
enPush.subscribeToTags(tagName: "<tag_name>") { response, statusCode, error in
   /**.....*/
});

Retrieve subscribed tags

The retrieveSubscriptionsWithCompletionHandler API returns the list of tags to which the device is subscribed. Use the following code snippets in the mobile application to get the subscription list.

// Get a list of tags that to which the device is subscribed.
enPush.retrieveSubscriptionsWithCompletionHandler { response, statusCode, error in
   /**.....*/
}

Unsubscribe from tags

The unsubscribeFromTags API removes the device subscription from the list tags. Use the following code snippets to allow your devices to get unsubscribe from a tag.

// unsubscibe from the given tag ,that to which the device is subscribed.
enPush.unsubscribeFromTags(tagName: "<tag_name>") { response, statusCode, error in
   /**.....*/
}

Receiving push notifications on iOS devices

To receive push notifications on iOS devices, add the following Swift method to the appDelegate.swift of your application:

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

   //UserInfo dictionary will contain data sent from the server
}

Notification options

The following notification options are supported.

Interactive notifications

  1. To enable interactive push notifications, the notification action parameters must be passed in as part of the notification object. The following is a sample code to enable interactive notifications:
let actionOne = ENPushNotificationAction(identifierName: "FIRST", buttonTitle: "Accept", isAuthenticationRequired: false, defineActivationMode: .foreground)

let actionTwo = ENPushNotificationAction(identifierName: "SECOND", buttonTitle: "Reject", isAuthenticationRequired: false, defineActivationMode: .destructive)

let category = ENPushNotificationActionCategory(identifierName: "category", buttonActions: [actionOne, actionTwo])

let notificationOptions = ENPushClientOptions()
notificationOptions.setInteractiveNotificationCategories(categoryName: [category])
enPush.initialize(instanceGUID, destinationID, apiKey, notificationOptions)
  1. Implement the callback method on AppDelegate.swift:

    func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) {
       switch response.actionIdentifier {
          case "Accept":
          print("Clicked Accept")
          case "Reject":
          print("Clicked Reject")
          default:
       }
       completionHandler()
    }
    

This callback method is invoked when user clicks the action button. The implementation of this method must perform tasks that are associated with the specified identifier and run the block in the completionHandler parameter.

Adding custom DeviceId for registration

To send DeviceId use the setDeviceId method of ENPushClientOptions class.

let options = ENPushClientOptions();
options.setDeviceId(deviceId: "YOUR_DEVICE_ID");

Remember to keep custom DeviceId unique for each device.

Enabling rich media notifications

Rich media notifications are supported on iOS 10 or later. To receive rich media notifications, implement UNNotificationServiceExtension. The extension will intercept and handle the rich media notification.

In the didReceive() method of your service extension, add the following code to retrieve the rich push notification content.

override func didReceive(_ request: UNNotificationRequest, withContentHandler contentHandler: @escaping (UNNotificationContent) -> Void) {
   self.contentHandler = contentHandler
   bestAttemptContent = (request.content.mutableCopy() as? UNMutableNotificationContent)
   ENPushRichPushNotificationOptions.didReceive(request, withContentHandler: contentHandler)
}

Send notifications to the iOS device

Use the Send Notification API to send the push notification for the iOS device. You can use the Node or Go admin SDK instead of calling the API directly.

Send notifications
Figure 27. Send notifications

Receive notifications
Figure 28. Receive notifications