Skip to main content

Apple Push Notification Implementation

Push Notification

IMPORTANT :

Make sure you have created APNS certificate and uploaded it to MoEngage dashboard as mentioned in APNS Certificate/ PEM file before testing push notification.

Adding Push Entitlement to your Project

First select your app target, then go to Capabilities . Here enable the Push Notifications capability for your app as shown below :

Uninstall Tracking

We make use of silent pushes to track uninstalls. For tracking uninstalls of all the user, enable Remote Notification background mode in app capabilities for the same as shown below :

NOTE:

On enabling Remote Notification background mode, we will be able to track uninstalls even for devices where push notification is disabled by the user.

Adding UserNotifications framework

In iOS10 MoEngage SDK(3.0.0 and above) uses UserNotifications framework for handling Push Notifications. In the App's Target add UserNotifications framework in Linked Frameworks and Libraries and set it Optional.

Registering for Push notification

From SDK version 3.0, for registering for push notifications, call registerForRemoteNotificationWithCategories: andCategoriesForPreviousVersions: andWithUserNotificationCenterDelegate: in your AppDelegate's application: didfinishlaunchingwithoptions: method :
if (@available(iOS 10.0, *)) {
        [[MoEngage sharedInstance] registerForRemoteNotificationWithCategories:nil withUserNotificationCenterDelegate:self];
} else {
        [[MoEngage sharedInstance] registerForRemoteNotificationForBelowiOS10WithCategories:nil];
}

Notification Actions

You can send the set of categories(UNNotificationCategory for iOS10 and MONotificationCategory for earlier versions of iOS) for supporting Notification actions. Get more info regarding notification actions here.
Now after registering for push, the below given callback methods will be called. Call the respective MoEngage SDK methods for the callbacks as shown below :
//Remote notification Registration callback methods
- (void)application:(UIApplication*)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData*)deviceToken {
 [[MoEngage sharedInstance] setPushToken:deviceToken];
}

-(void)application:(UIApplication *)application didFailToRegisterForRemoteNotificationsWithError:(NSError *)error {
 [[MoEngage sharedInstance]didFailToRegisterForPush];
}

//This method is for getting the types of notifications that app may use 
-(void)application:(UIApplication *)application didRegisterUserNotificationSettings:(UIUserNotificationSettings *)notificationSettings{
    
 [[MoEngage sharedInstance]didRegisterForUserNotificationSettings:notificationSettings];
}

Whitelist App For Deeplinking:

While implementing deeplinks, make sure that you have added the apps URL Scheme to LSApplicationQueriesSchemes array in Info.plist to whitelist your app. Without this the deeplinks won't work post iOS9.

Callback methods on receiving push Notification

Include calls to MoEngage SDK methods on receiving notification callbacks as shown below:
// UserNotifications Framework Callback for iOS10 and above
- (void)userNotificationCenter:(UNUserNotificationCenter *)center
       willPresentNotification:(UNNotification *)notification
         withCompletionHandler:(void (^)(UNNotificationPresentationOptions options))completionHandler{
    completionHandler((UNNotificationPresentationOptionSound
                       | UNNotificationPresentationOptionAlert ));
}

- (void)userNotificationCenter:(UNUserNotificationCenter *)center
didReceiveNotificationResponse:(UNNotificationResponse *)response
         withCompletionHandler:(void (^)())completionHandler{
           
    [[MoEngage sharedInstance] userNotificationCenter:center didReceiveNotificationResponse:response];
    //Custom Handler
    NSDictionary *pushDictionary = response.notification.request.content.userInfo;
    if (pushDictionary) {
        [self customPushHandler:pushDictionary];
    }
    completionHandler();
}

//Remote notification received callback method for iOS versions below iOS10
- (void) application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo {
        [[MoEngage sharedInstance]didReceieveNotificationinApplication:application withInfo:userInfo openDeeplinkUrlAutomatically:YES];
}
Method userNotificationCenter:willpresentnotification:withCompletionHandler: is called when the app receives notification in foreground. Here, in the completion handler you can mention how you want to let the user know that the app has received a notification.
Method userNotificationCenter:didreceivenotificationresponse:withCompletionHandler is called when the app receives a response from the user. Response can be Default Click on the Notification or Dismissing the notification or any of the other custom actions implemented using UNUserNotificationCategory. Here, call userNotificationCenter:didreceivenotificationresponse: of MoEngage class.

Notification Dismissed Tracking:

Notification dismissed action can be tracked only if UNUserNotificationCenter delegate methods are part of implementation.

UNUserNotificationCenter delegate methods

Note : userNotificationCenter:didreceivenotificationresponse:withCompletionHandler is the only method called when the user clicks on notification, if implemented. Therefore, include your custom handlers here instead of application:didreceiveremotenotification: for iOS10.

Test/Live Builds

  • If you are testing the app on Test Flight or on a live app store build, make sure you upload the adhoc or production pem to our dashboard. And also in this case you have to send push notifications from Live environment of your account.
  • For dev build, you can upload development or production certificate in dashboard, but make sure that you create your campaign in Test environment, as you cannot send push notifications to dev build from Live environment.

Notification Payload

While sending push notifications, you can add key value pairs to your notification payload. An example of the push payload is :
{
    "app_extra" =     {
        moe_deeplink = "moe://screen/settings";
        screenData =         {
            key1 = val1;
            key2 = val2;
        };
        screenName = "";
    };
    aps =     {
        alert = {
          title = "Title";
          subtitle = "Subtitle";
          body = "Hello iOS Tutorial Point";
        };
        mutable-content = 1;
        badge = 1;
    };
  
  // Do not use any keys under iOS Tutorial Point. They are for internal purposes.    iOS Tutorial Point =     {
        cid    = 55f2ba15a4ab4104a287bf88;
       webUrl  = "https://www.google.com";
        media-attachment = "http://s32.iamwire.com.s3.amazonaws.com/wp-content/uploads/2015/09/MoEngage.jpg";
       media-type = "image";
    };
}

Use of screenName

The possible values for screenName parameter is something which you will have to define in your project. It will be present in the notification payload. And you will have to implement the part to parse and get screenName parameter's value and to navigate to the mentioned screen.
  • DeepLinking
    The moe_deeplink parameter will contain deeplinking URL to open. From SDK version 2.2 we support automatic deep linking from the SDK. If the campaign created had a deeplink field and the initialize method in App Delegate had openDeeplinkUrlAutomatically set to true, the SDK will call handleOpenUrl with the specified deep link.For older SDK's, you can use your own key value pair or make use of screenName parameter to define which screen to navigate to.

Define Valid URL Schemes for DeepLinks (LSApplicationQueriesSchemes)

LSApplicationQueriesSchemes(Array - iOS) Specifies the URL schemes you want the app to be able to use with the canOpenURL: method of the UIApplication class(which is being used in our SDK). For each URL scheme you want your app to use with the deeplinks, add it as a string in this array in Info.plist. For more info follow this link.
  • Coupon Code
    If you wish to send a coupon code to your user, add a key "couponCode" in the payload, with the value as the coupon. For e.g. couponCode - ZEF30.
    When the user clicks on the push notification, he/she will be shown an alert that Coupon Code ZEF30 is copied to your clipboard.
  • Rich Landing
    If you wish to open a web page inside the app, from a push notification, add a key "webUrl" in the payload, with the value as the url. For e.g. webUrl - https://www.google.com.
    When the user clicks on the push notification, he/she will see a webpage (WebView) inside the app with the url opened.
  • Rich Notifications (iOS10)
    The "media-attachment" key in the payload gives you the URL of the media which you can download and show in the notification and "media-type" key gives you the type of media of which the URL is provided. Get more info on this here.

HTTP URLs

Http URL's aren't supported in iOS9 unless explicitly specified in the plist. You will have include App Transport Security Settings Dictionary in your Info.plist and inside this set Allow Arbitrary Loads to YES.

Comments

Popular Posts

React Native: How To Open App Settings Page

  React Native: How To Open App Settings Page React Native has a Linking module to manage the interaction with other applications in the device. In this article, I will explain how you can open “Application Setting Page” of the device using. Sample Case Before I explain how to do this, I’ll talk about an example case where we might need this: You need to get location permission within the application from a user using an iOS operating system and you asked for permission. But user did not agree to grant this permission the first time. In this case, you cannot ask your user for location permission the second time. In this case, the only thing to do is to direct the user to the settings page of our application and make it manually allow it. Now that we have explained our example situation, we can move on to how we can redirect our user to the “settings page of our application”. Open App Settings Page iOS If our user is using an iOS operating system, we can handle the whole process wit...

Integrate the FaceID or TouchID Authentication in iOS Apps - Swift

FaceID or TouchID Authentication Dear Folks, today I am going to explain the proper way to integrate the Face ID or Touch ID in iOS App. Face ID and Touch ID are secure, familiar authentication methods that people trust. Follow below steps: Step 1: Add NSFaceIDUsageDescription Key in info.plist file <key>NSFaceIDUsageDescription</key> <string>This app requires Face ID permission to authenticate using Face recognition.</string> Step 2: Create a swift file with any name but it would be better to related to its functionality, Like BioMetrixFile.swift Step 3: In BioMetrixFile write below codes and follow instructions. But before proceeding further import LocalAuthentication class in BioMetrixFile. Now, create typealias for success or failure blocks to well manage Authentication Success or Failure. public typealias AuthenticationSuccess = (() -> ()) public typealias AuthenticationFailure = ((AuthenticationError) -> ()) Now written all s...

Add Custom Checkbox on UITableViewCell or UITableView in Swift 4

Add Custom Checkbox Introduction to how to add custom checkbox on UITableViewCell or UITableView in swift 4 In this tutorial, we are going to learn about how can we create or add custom checkbox on UITableViewCell or UITableView in swift and perform IBAction on our custom checkbox placed on UITableViewCell or UITableView in swift 4. We will place UIButton on UITableViewCell that will act as checkbox for our UITableViewCell in UITableView using swift 4. In the end of this tutorial, we will have output as shown in below picture Learn how to create checkbox in swift from  HERE Steps to create or add custom checkbox on UITableViewCell or UITableView Step 1 :  Create a new Xcode project and select  "Single View App"  template. Name  project as  "addCheckBoxonTable-Tutorial" . Step 2:  Open  "Main.storyboard"  file and drag UITableView object on to the view. Then we will add constraints to UITableView so that it fits...