Creating and sending 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.
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
Regionfrom the list of supported regions and select apricing 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 -
Go to
Identifiers > Add identifier button.
Identifier Button -
Click add a new
Identifierbutton.
Add new Identifier button -
Select the App IDs option.
App IDs option -
Select a type and click
Continue.
App ID type -
Provide a string for the App ID Prefix. Provide the App name in the
Descriptionfield. 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 -
Select the
Push Notificationscheck-box from the Capabilities and clickContinue.
Enable Push Notifications -
Go through your settings and click
Register > Done.
Your App ID is now registered.
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 -
In the
Identifiers area, select your App ID.
Identifiers tab -
Select the
Push Notificationscheck-box OR select theEditoption.
Push Notifications check-box - On Development SSL certificate pane, click Create Certificate...
- On Production SSL certificate pane, click Create Certificate...
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 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 diskto download the.certSigningRequestfile to your Mac, then clickContinue.
Certificate details -
In the
Save Asmenu option, name the.certSigningRequestfile, select the location where the file must be saved, and clickSave.
Save CSR file -
Click
Done. You now have a CSR.
CSR created -
Go back to the Apple developer portal, for the Upload CSR file option, click Choose File, and select file
CertificateSigningRequest.certSigningRequest. ClickContinue.
Upload CSR file -
Click
Download. Theaps_development.cerfile is downloaded.
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
Exportto convert the certificate into the personal information exchange format (.p12format).
Export certificate -
In the
Save Asfield, provide the certificate a meaningful name. For example, sandbox-apns.p12 or production-apns.p12, then clickSave.
Save certificate -
In the
Enter a passwordfield, enter a password to protect the exported items, then clickOK. You can use this password to configure your APNs settings on the Event Notifications service console.
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 -
Go to
Keystab.
Keys tab -
Enter
Key Nameand enable APNs, clickcontinue.
P8 token details -
Click
Register.
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
Sourcessection of the Event Notifications dashboard. - Click
Addand 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: selectiOS Push Notificationstype 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 Typeand selectEnvironment.- if certificate type is
p8, upload .p8 file and provideKeyID,TeamID, andBundleID. - if certificate type is
p12, upload p12 certificate and provide certificatepassword.
- if certificate type is
- 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 typeselect 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. Jsonpath expressions can be validated at jsonpath.com or extendsclass.com.
Create an Event Notifications subscription
Click Subscriptions in the Event Notifications console. Enter the following subscription details:
ClickCreate 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 topicsection, select a topic from the drop-down list and select a destination from the destination drop-down list. Destination type: select type underDestinationand clickAdd.
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.
-
Add the
importstatements in your.swiftfile.import ENPushDestination -
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
userIdbased 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
userIdis used to pass the uniqueuserIdvalue 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
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
- 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)
-
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.