iOS SDK integration


Subscribe to RSS Channel

Step 1: Import the Pushbots.framework into your Xcode project using Cocoapods or manually:


The easiest way to install Pushbots library into your iOS project using CocoaPods:

Xcode 7+ and iOS 7.0+ are required.
platform :ios, '7.0'
pod 'Pushbots', '~> 2.0.4'

1.1. Download and extract framework .

Xcode 7+ and iOS 7.0+ are required.

1.2. The library requires your application to link against the following Frameworks:
SystemConfiguration.framework
CoreTelephony.framework
(Show me how ?).

1.3. Drag Pushbots.framework folder into frameworks group , and check 'copy items into destination group's folder '


Step 2: Add required code:


Enable Push notifications in Capabilities tab (xcode 8+):

2.1: Objective-C project


2.1.1: Open AppDelegate.h and import Pushbots framework:

#import <Pushbots/Pushbots.h>

2.1.2: Define PushbotsClient property:

@property (strong, nonatomic) Pushbots *PushbotsClient;

2.1.3: Open AppDelegate.m initialize Pushbots framework in didFinishLaunchingWithOptions, and replace appID with your from application settings:

self.PushbotsClient = [[Pushbots alloc] initWithAppId:@"PUSHBOTS_APP_ID" prompt:YES];

2.1.4: Add the methods didRegisterForRemoteNotificationsWithDeviceToken and didFailToRegisterForRemoteNotificationsWithError to Appdelegate.m to register the device and update its info on Pushbots server:

- (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken {
	// Register the deviceToken on Pushbots
	[self.PushbotsClient registerOnPushbots:deviceToken];
}

-(void)application:(UIApplication *)application didFailToRegisterForRemoteNotificationsWithError:(NSError *)error{
	NSLog(@"Notification Registration Error %@", [error description]);
}

2.2: Swift project


2.1. Right click on project title and choose New File...

2.2.Under iOS > Source > Objective-C file, then click on Next.

2.3.Type any name, then click on Next.

2.4.Choose Create Bridging Header:

2.5. Right click on the created file then move it to trash.

2.6. Open {ProjectTitle}-Bridging-Header.h file and import pushbots framework:

#import <Pushbots/Pushbots.h>

2.2.2: Open AppDelegate initialize Pushbots framework in didFinishLaunchingWithOptions, and replace appID with your from application settings:

_ = Pushbots(appId:"PUSHBOTS_APP_ID", prompt: true);

2.1.4: Add the methods didRegisterForRemoteNotificationsWithDeviceToken and didFailToRegisterForRemoteNotificationsWithError to Appdelegate.swift to register the device and update its info on Pushbots server:

func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
    // This method will be called everytime you open the app
    // Register the deviceToken on Pushbots
    Pushbots.sharedInstance().register(onPushbots: deviceToken);
}

func application(_ application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: Error) {
    print("Notification Registration Error \(error)")
}

Step 3: Handling incoming notifications:


iOS apps will receive notifications differently depending its state:

1. When app is not running:

Add this line to didFinishLaunchingWithOptions to track notification opens:

//Track Push notification opens while launching the app form it
[self.PushbotsClient trackPushNotificationOpenedWithLaunchOptions:launchOptions];
//Track Push notification opens while launching the app form it
Pushbots.sharedInstance().trackPushNotificationOpened(launchOptions: launchOptions);

Also Notification will be passed to didFinishLaunchingWithOptions method, here's how to capture it:

NSDictionary *userInfo = [launchOptions objectForKey:UIApplicationLaunchOptionsRemoteNotificationKey];
if (userInfo) {
	//Check for openURL [optional]
    //[Pushbots openURL:userInfo];
	//Capture notification data e.g. badge, alert and sound
    NSDictionary *aps = [userInfo objectForKey:@"aps"];

    if (aps) {
        NSString *alertMsg = [aps objectForKey:@"alert"];
        NSLog(@"Notification message: %@", alertMsg);
    }
	
	//Capture custom fields
    NSString* articleId = [userInfo objectForKey:@"articleId"];
}
if launchOptions != nil {
if let userInfo = launchOptions![UIApplicationLaunchOptionsKey.remoteNotification] as? NSDictionary {
    //Capture notification data e.g. badge, alert and sound
    if let aps = userInfo["aps"] as? NSDictionary {
        let alert = aps["alert"] as! String
        print("Notification message: ", alert);
        //UIAlertView(title:"Push Notification!", message:alert, delegate:nil, cancelButtonTitle:"OK").show()
    }
    
    //Capture custom fields
    if let articleId = userInfo["articleId"] as? NSString {
        print("ArticleId: ", articleId);
    }
}
}

2. When app is running:

The notificaiton will be captured in didReceiveRemoteNotification, add this method to AppDelegate.m to track it:

- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo
{
	//Check for openURL [optional]
    [Pushbots openURL:userInfo];
    //Track notification only if the application opened from Background by clicking on the notification.
    if (application.applicationState == UIApplicationStateInactive) {
        [self.PushbotsClient trackPushNotificationOpenedWithPayload:userInfo];
    }

    //The application was already active when the user got the notification, just show an alert.
    //That should *not* be considered open from Push.
    if (application.applicationState == UIApplicationStateActive) {
        NSDictionary *notificationDict = [userInfo objectForKey:@"aps"];
        NSString *alertString = [notificationDict objectForKey:@"alert"];
        UIAlertView *alert = [[UIAlertView alloc]
                              initWithTitle:@"Push Notification Received" message:alertString delegate:self
                              cancelButtonTitle:@"Cancel" otherButtonTitles:@"Ok", nil];
        [alert show];
    }
}
func application(_ application: UIApplication,  didReceiveRemoteNotification userInfo: [AnyHashable : Any],  fetchCompletionHandler handler: @escaping (UIBackgroundFetchResult) -> Void) {
	//Track notification only if the application opened from Background by clicking on the notification.
    if application.applicationState == .inactive  {
        Pushbots.sharedInstance().trackPushNotificationOpened(withPayload: userInfo);
    }
    
    //The application was already active when the user got the notification, just show an alert.
    //That should *not* be considered open from Push.
    if application.applicationState == .active  {
        //Capture notification data e.g. badge, alert and sound
        if let aps = userInfo["aps"] as? NSDictionary {
            let alert_message = aps["alert"] as! String
            let alert = UIAlertController(title: alertDic["title"] as? String,
                                          message: alert_message,
                                          preferredStyle: .alert)
            let defaultButton = UIAlertAction(title: "OK",
                                              style: .default) {(_) in
                                                // your defaultButton action goes here
            }
            
            alert.addAction(defaultButton)
            self.window?.rootViewController?.present(alert, animated: true) {
                // completion goes here
            }
        }
    }
}

Step 4: Silent notifications:

When a silent notification arrives, iOS wakes up your app in the background so that you can get new data from your server or do background information processing. Users arenโ€™t told about the new or changed information that results from a silent notification, but they can find out about it the next time they open your app.

1. Go to the project/capabilities and enable Background Modes and the Remote notifications option.

2. Add this method to your AppDelegate:

- (void)application:(UIApplication *)application
didReceiveRemoteNotification:(NSDictionary *)userInfo  fetchCompletionHandler:(void (^)(UIBackgroundFetchResult))handler {
    // .. Process notification data
    handler(UIBackgroundFetchResultNewData);
}
func application(_ application: UIApplication,  didReceiveRemoteNotification userInfo: [NSObject : AnyObject],  fetchCompletionHandler handler: (UIBackgroundFetchResult) -> Void) {
    // .. Process notification data
    handler(UIBackgroundFetchResult.newData)
}

2. Set Silent Push option while sending notificaton from dashboard, or use the custom field "silent_push" in API to send a silent notification.