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

How I Reduced the Size of My React Native App by 85%

How and Why You Should Do It I borrowed 25$ from my friend to start a Play Store Developer account to put up my first app. I had already created the app, created the assets and published it in the store. Nobody wants to download a todo list app that costs 25mb of bandwidth and another 25 MB of storage space. So today I am going to share with you how I reduced the size of Tet from 25 MB to around 3.5 MB. Size Matters Like any beginner, I wrote my app using Expo, the awesome React Native platform that makes creating native apps a breeze. There is no native setup, you write javascript and Expo builds the binaries for you. I love everything about Expo except the size of the binaries. Each binary weighs around 25 MB regardless of your app. So the first thing I did was to migrate my existing Expo app to React Native. Migrating to React Native react-native init  a new project with the same name Copy the  source  files over from Expo project Install all de...

How to recover data of your Android KeyStore?

These methods can save you by recovering Key Alias and Key Password and KeyStore Password. This dialog becomes trouble to you? You should always keep the keystore file safe as you will not be able to update your previously uploaded APKs on PlayStore. It always need same keystore file for every version releases. But it’s even worse when you have KeyStore file and you forget any credentials shown in above box. But Good thing is you can recover them with certain tricks [Yes, there are always ways]. So let’s get straight to those ways. 1. Check your log files → For  windows  users, Go to windows file explorer C://Users/your PC name/.AndroidStudio1.4 ( your android studio version )\system\log\idea.log.1 ( or any old log number ) Open your log file in Notepad++ or Any text editor, and search for: android.injected.signing and if you are lucky enough then you will start seeing these. Pandroid.injected.signing.store.file = This is  file path where t...

Video Calling In IOS Objective C

Video Calling Sources Project homepage on GIT — https://github.com/QuickBlox/quickblox-ios-sdk/tree/master/sample-videochat-webrtc Download ZIP - https://github.com/QuickBlox/quickblox-ios-sdk/archive/master.zip Overview The VideoChat code sample allows you to easily add video calling and audio calling features into your iOS app. Enable a video call function similar to FaceTime or Skype using this code sample as a basis. It is built on the top of WebRTC technology.            System requirements The QuickbloxWebRTC.framework supports the next:     * Quickblox.framework v2.7 (pod QuickBlox)     * iPhone 4S+.     * iPad 2+.     * iPod Touch 5+.     * iOS 8+.     * iOS simulator 32/64 bit (audio might not work on simulators).     * Wi-Fi and 4G/LTE connections. Getting Started with Video Calling API Installation with CocoaPods CocoaPods is a dependency manag...