Getting started

You are currently viewing the AWS SDK for Mobile documentation which is a collection of low-level libraries. Use the Amplify libraries for all new app development. Learn more

You can view the Mobile SDK API reference here.

Enable your users to receive mobile push messages sent from the Apple (APNs) and Google (FCM/GCM) platforms. The Amplify CLI deploys your push notification backend using Amazon Pinpoint. You can also create Amazon Pinpoint campaigns that tie user behavior to push or other forms of messaging.

Set Up Your Backend

Prerequisites

  1. Complete the Get Started steps before you proceed.

  2. On Xcode, under the target, select "Signing & Capabilities", make sure the Bundle Identifier is unique. Make sure Automatically manage signing is enabled and your apple developer team is chosen.

  3. Plug in the device and make sure it is registered and there are no errors on this page provisioning the profile.

  4. Click on + Capability, and add Push Notification and Background Modes. For Background Modes, have Remote notifications checked.

Step-by-step

  1. Set up a new Amplify project, you can skip this step if you are using an existing one:

    1amplify init
  2. Add analytics to your app to allow guests and unauthenticated users to send analytics events:

    1amplify add analytics
  3. Provision the backend:

    1amplify push

Connect to Your Backend

Use the following steps to connect push notification backend services to your app.

  1. Add the following pods to your Podfile:

    1target :'YOUR-APP-NAME' do
    2 use_frameworks!
    3 pod 'AWSPinpoint'
    4 pod 'AWSMobileClient'
    5end

    Run pod install --repo-update before you continue.

  2. Open the .xcworkspace file.

  3. Make sure the project contains the awsconfiguration.json file and it is added to Xcode (by dragging it in with copy as needed checked). It should be generated when you set up your backend.

  4. Make sure the app builds.

  5. Add the following import statements to your AppDelegate file:

    1import UserNotifications
    2import AWSPinpoint
  6. In the AppDelegate file, inside application(_:didFinishLaunchingWithOptions:), initialize an AWSPinpoint instance and register for push notifications from the user. When the app runs, the user will be prompt with a modal to allow notifications. We recommend you request for authorization from the user during app startup, so your users can begin receiving notifications as early as possible.

    1class AppDelegate: UIResponder, UIApplicationDelegate {
    2 var pinpoint: AWSPinpoint?
    3
    4 func application(
    5 _: UIApplication,
    6 didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?
    7 ) -> Bool {
    8 // Instantiate Pinpoint
    9 let pinpointConfiguration = AWSPinpointConfiguration
    10 .defaultPinpointConfiguration(launchOptions: launchOptions)
    11 // Set debug mode to use APNS sandbox, make sure to toggle for your production app
    12 pinpointConfiguration.debug = true
    13 pinpoint = AWSPinpoint(configuration: pinpointConfiguration)
    14
    15 // Present the user with a request to authorize push notifications
    16 registerForPushNotifications()
    17
    18 return true
    19 }
    20
    21 // MARK: Push Notification methods
    22
    23 func registerForPushNotifications() {
    24 UNUserNotificationCenter.current().delegate = self
    25 UNUserNotificationCenter.current()
    26 .requestAuthorization(options: [.alert, .sound, .badge]) { [weak self] granted, _ in
    27 print("Permission granted: \(granted)")
    28 guard granted else { return }
    29
    30 // Only get the notification settings if user has granted permissions
    31 self?.getNotificationSettings()
    32 }
    33 }
    34
    35 func getNotificationSettings() {
    36 UNUserNotificationCenter.current().getNotificationSettings { settings in
    37 print("Notification settings: \(settings)")
    38 guard settings.authorizationStatus == .authorized else { return }
    39
    40 DispatchQueue.main.async {
    41 // Register with Apple Push Notification service
    42 UIApplication.shared.registerForRemoteNotifications()
    43 }
    44 }
    45 }
    46}

    Make sure the app builds, runs and prompts the user for notification authorization.

  7. Add the AppDelegate methods to listen on the callbacks from UIApplication.shared.registerForRemoteNotifications(). Either application(_:didRegisterForRemoteNotificationsWithDeviceToken:) will be called indicating successfully registering with APNS or application(_:didFailToRegisterForRemoteNotificationsWithError:) indicating a failure. On successfully registering with APNS, pass the device token to AWS pinpoint to register the endpoint

    1// MARK: Remote Notifications Lifecycle
    2func application(_: UIApplication,
    3 didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
    4 let tokenParts = deviceToken.map { data in String(format: "%02.2hhx", data) }
    5 let token = tokenParts.joined()
    6 print("Device Token: \(token)")
    7
    8 // Register the device token with Pinpoint as the endpoint for this user
    9 pinpoint?.notificationManager
    10 .interceptDidRegisterForRemoteNotifications(withDeviceToken: deviceToken)
    11}
    12
    13func application(_: UIApplication,
    14 didFailToRegisterForRemoteNotificationsWithError error: Error) {
    15 print("Failed to register: \(error)")
    16}
  8. Build and run the app. You should see the device token printed out.

  9. To handle push notifications, add application(_:didReceiveRemoteNotification:fetchCompletionHandler:).

    1func application(
    2 _ application: UIApplication,
    3 didReceiveRemoteNotification userInfo: [AnyHashable: Any],
    4 fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void
    5) {
    6 // if the app is in the foreground, create an alert modal with the contents
    7 if application.applicationState == .active {
    8 let alert = UIAlertController(title: "Notification Received",
    9 message: userInfo.description,
    10 preferredStyle: .alert)
    11 alert.addAction(UIAlertAction(title: "Ok", style: .default, handler: nil))
    12
    13 UIApplication.shared.keyWindow?.rootViewController?.present(
    14 alert, animated: true, completion: nil
    15 )
    16 }
    17
    18 // Pass this remote notification event to pinpoint SDK to keep track of notifications produced by AWS Pinpoint campaigns.
    19 pinpoint?.notificationManager.interceptDidReceiveRemoteNotification(
    20 userInfo, fetchCompletionHandler: completionHandler
    21 )
    22
    23 // Pinpoint SDK will not call the `completionHandler` for you. Make sure to call `completionHandler` or your app may be terminated
    24 // See https://developer.apple.com/documentation/uikit/uiapplicationdelegate/1623013-application for more details
    25 completionHandler(.newData)
    26}

    For iOS 10 and above, pass the notification event to pinpoint SDK in userNotificationCenter(_:willPresent:withCompletionHandler:) and userNotificationCenter(_:didReceive:withCompletionHandler:).

    1extension AppDelegate: UNUserNotificationCenterDelegate {
    2 func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: (UNNotificationPresentationOptions) -> Void) {
    3 // Handle foreground push notifications
    4 pinpoint?.notificationManager.interceptDidReceiveRemoteNotification(notification.request.content.userInfo, fetchCompletionHandler: { _ in })
    5
    6 // Make sure to call `completionHandler`
    7 // See https://developer.apple.com/documentation/usernotifications/unusernotificationcenterdelegate/1649518-usernotificationcenter for more details
    8 completionHandler(.badge)
    9 }
    10
    11 func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: () -> Void) {
    12 // Handle background and closed push notifications
    13 pinpoint?.notificationManager.interceptDidReceiveRemoteNotification(response.notification.request.content.userInfo, fetchCompletionHandler: { _ in })
    14
    15 // Make sure to call `completionHandler`
    16 // See https://developer.apple.com/documentation/usernotifications/unusernotificationcenterdelegate/1649501-usernotificationcenter for more details
    17 completionHandler()
    18 }
    19}
  10. (Optional) Enable verbose logging for AWSPinpoint SDK. The endpointId will be printed out when verbose logging is turned on. It will be useful when testing push notification events with AWS Pinpoint campaigns but not required.

    Add this to application(_:didFinishLaunchingWithOptions:)

    1AWSDDLog.sharedInstance.logLevel = .verbose
    2AWSDDLog.add(AWSDDTTYLogger.sharedInstance)

Manual Configuration

As an alternative to automatic configuration using the Amplify CLI, you can manually enter the necessary configurations. Here is a snippet of the relevant sections of the awsconfiguration.json file:

1{
2 "Version": "0.1.0",
3 "IdentityManager": {
4 "Default": {}
5 },
6 "CredentialsProvider": {
7 "CognitoIdentity": {
8 "Default": {
9 "PoolId": "COGNITO-IDENTITY-POOL-ID",
10 "Region": "COGNITO-IDENTITY-POOL-REGION"
11 }
12 }
13 },
14 "CognitoUserPool": {
15 "Default": {
16 "PoolId": "COGNITO-USER-POOL-ID",
17 "AppClientId": "COGNITO-USER-APP-CLIENT-ID",
18 "Region": "COGNITO-USER-POOL-REGION"
19 }
20 },
21 "PinpointAnalytics": {
22 "Default": {
23 "AppId": "PINPOINT-APP-ID",
24 "Region": "PINPOINT-REGION"
25 }
26 },
27 "PinpointTargeting": {
28 "Default": {
29 "Region": "PINPOINT-REGION"
30 }
31 }
32}

Make the following changes to the configuration file. The values are available in the AWS Console.

  • CognitoIdentity
    • Replace COGNITO-IDENTITY-POOL-ID with the identity pool ID.
    • Replace COGNITO-IDENTITY-POOL-REGION with the Region the identity pool was created in.
  • CognitoUserPool
    • Replace COGNITO-USER-POOL-ID with the user pool ID.
    • Replace COGNITO-USER-POOL-REGION with the Region the user pool was created in.
    • Replace COGNITO-USER-APP-CLIENT-ID with the app client id that has access to the user pool.
    • Replace COGNITO-USER-POOL-APP-CLIENT-SECRET with the app client secret for the app client id.
    • Replace COGNITO-USER-POOL-REGION with the Region the user pool was created in.
  • PinpointAnalytics
    • Replace PINPOINT-APP-ID with the Project Id of the Pinpoint project.
    • Replace PINPOINT-REGION with the Region the Pinpoint project was created in.
  • PinpointTargeting
    • Replace PINPOINT-REGION with the Region the Pinpoint project was created in.

Add Amazon Pinpoint Targeted and Campaign Push Messaging

The Amazon Pinpoint console enables you to target your app users with push messaging. You can send individual messages or configure campaigns that target a group of users that match a profile that you define. For instance, you could email users that have not used the app in 30 days, or send an SMS to those that frequently use a given feature of your app.

The following steps show how to send push notifications targeted for your app.

  1. Go to https://developer.apple.com/account/

  2. Under "Certificates, Identifiers & Profiles", on the left side click on "Keys", click +, type in a name like "Push Notification Key", check off Apple Push Notification Service (APNs). Register and download the file. It should be in the format of AuthKey_<Key ID>.p8

  3. Go to your "Membership details" page to get the "Team ID"

  4. Run amplify notifications add

    1? Choose the push notification channel to enable. `APNS`
    2? Choose authentication method used for APNs `Key`
    3? The bundle id used for APNs Tokens: <Your App's BundleID like com.yourname.projectname>
    4? The team id used for APNs Tokens: `XXXXXXXXX`
    5? The key id used for APNs Tokens: `ABCDEXXXXX`
    6? The key file path (.p8): `AuthKey_ABCDEXXXXX.p8`
    7The APNS channel has been successfully enabled.
  5. Open the AWS Pinpoint console with amplify console analytics

  6. Go to Campaign, click Create Campaign, provide a campaign name, and select Push Notifications as the channel, and click next.

  7. In the segment section, select Create a segment and you should see 1 device as a targeted endpoint, which is the app you are running on the device. Choose this option and then choose Next Step.

  8. Provide text for a sample title and body for the push notification, enter the device token or endpoint ID retrieved from the app.

    • Make sure the app is in the foreground, click on Test message and you should see an alert modal pop up with your test message wrapped in push notification data.
    • Make sure the app is in the background, click on Test message and you should see push notification slide down from the top.

Campaign Push messaging events

When a user receives an notification and taps on it, the AWS Pinpoint SDK will send a corresponding event that you can filter on in the AWS Pinpoint console.

_campaign.opened_notification event will be sent when the notification is opened from an app Inactive or Terminated state.

_campaign.received_foreground when the app is received while it is in the foreground

_campaign.received_background when the notification is tapped on while the app is in the background

If the developer never taps on the notification even though it was received on the device, the App will not submit an event for that since there is no way for the App to know that the notification was received by the device.