Search This Blog

Wednesday, July 29, 2015

Notification for PushBot

Ref: https://pushbots.com/developer/docs/ios#Sandbox               

Creating an App ID

       
    1. Log in to the Apple developer center and click App IDs , then Click on Add App ID icon [].    
2. Fill AppID Form:
  • Enter your App ID Description (Name).
  • Check Explicit App ID.
  • Enter your Bundle ID.
  • Check Push Notifications.
  • Click Continue:
   
    Ensure you have created an App ID without a wildcard. Wildcard IDs cannot use the push notification service.
Do not confuse the app identifier and the bundle identifier.
The bundle identifier is something like: com.company.appname and is defined by an app's info.plist.
   
    3. Confirm App ID settings. Click Submit:
   

Generating Push Certificate

    1. Open App IDs page
  1. Click on App IDs.
  2. Click on the App ID you've just created.
  3. Click on Edit.
                   
    2. Scroll to Push Notifications section and click on Create Certificate ,
A wizard will appear guiding you through the steps to generate a signing authority and then upload it to the portal, then download the newly generated certificate. This step is also covered in the Apple documentation.
You’ll notice that there are two certificates listed – one for development and the other for production. The APNS has test servers and live production servers. Each uses and requires a different client SSL certificate. The test servers can be used to send pushes to apps built with development provisioning profiles; the production servers can be used to send pushes to apps built with distribution provisioning profiles (Ad Hoc, In House, or App Store builds).    
If you wanna switch to production check out: Moving from Development to production
           
    3. We'll create Certificate Signing Request (CSR) file now.
In the Applications folder on your Mac, open the Utilities folder and launch Keychain Access.    
           
    4. Within the Keychain Access drop down menu, select Keychain Access > Certificate Assistant > Request a Certificate from a Certificate Authority.                   
           
    5. In the Certificate Information window, enter the following information:
In the User Email Address field, enter your email address
In the Common Name field, create a name for your private key
(eg. John Doe Dev Key)
Select the 'Saved to disk' option
Click Continue within Keychain Access to complete the CSR generating process .                   
       
    6.Let's go back to Apple developer portal, click on Continue and Select the Certificate Signing request (CSR) file you've just created, then click on Generate and finally click on Done.                               
    7. Scroll down to Push Notifications section and click on Download besides the certificate you've just created.               
           
    8. Launch Keychain again.
  • Filter keychains by Login
  • Filter Category by Certificates
  • Import your aps_[development/production].cer into your Keychain by dragging and dropping it into login section in keychain.
You will see an expandable option called “Apple Development/Production IOS Push Services : com.**.** ”.                                    
    9.Expand this option then right click on “Apple Development/Production IOS Push Services : com.**.** ” > Export “Apple Development/Production IOS Push Services : com.**.** ”.                   
           
    10. Save file as apns-dev-cert.p12 somewhere you can access it, leave password field empty, as pushbots won't accept certificates with password.
                       
       
    11. Enter your admin password to confirm and click on Allow finalize the export process:    
               
   
        apns-dev-cert.p12 is the certificate file you're going to upload on PushBots.
The same process above applies when generating the production certificate.    

Create iOS provisioning profile

    1. Open iOS Provisioning Profile page, and click on Add Profile icon [].
    2. A wizard will appear to guide you through creating iOS provisioing profile    
  1. Choose provisioning Profile Type [Development or Distribution].
  2. Click Continue.
                           
    3. Select App ID you have just created , then Click Continue.                    
       
    4. Check your iOS Development certificate [auto generated by xcode] , then Click Continue.                   
               
    5. Check Devices , then Click Continue.                       
           
    6. Name the profile [Your app name - (production/development)], then Click Generate.                       
           
    7. Finally, Download the Profile.                   
           
    8. Double click on the Profile, to load in xcode.    

Create xcode project

    1. Open Xcode, open File > New > Project [cmd+shift+N].    
  • Enter your App name
  • Make sure Bundle Identifer is the same as the app ID of your push cretificate.    
                                           
    2. Go to Project Settings
   
  1. Click on Project title.
  2. Click on project title below targets.
  3. Click on Build Settings.
  4. Find Code Signing in settings
  5. Update your Code Signing Identity.
                       
  1. Find Provisioing Profile in settings below Code Signing
  2. Update your it with the profile you've just created.
   

Installing the library

   
       
       
           
                The easiest way to install Pushbots library into your iOS project using CocoaPods.                
               
pod 'Pushbots', '~> 1.1.0'
                   
           
   

Importing the library

Objective-C project

Open AppDelegate.m import Pushbots framework
#import <Pushbots/Pushbots.h>

Swift project

    1. Right click on project title and choose New File...                        
    2.Under iOS > Source > Objective-C file, then click on Next.                        
    3.Type any name, then click on Next.                        
    4.Choose Yes, to create the bridging header.                        
    5. Right click on the created file then delete it.                        
    6. Open {ProjectTitle}-Bridging-Header.h file and import pushbots framework:    
#import <Pushbots/Pushbots.h>

Implementing the library

    1. Open AppDelegate.m/swift initialize Pushbots framework in didFinishLaunchingWithOptions:        
  •             Objective-C        
  •             Swift        
       
       
                       
[Pushbots sharedInstanceWithAppId:@"54f4a0fe1d0ab1e3168b678"];
//Handle notification when the user click it, while app is closed.
//This method will show an alert to the user.
[[Pushbots sharedInstance] receivedPush:launchOptions];
       
           
                   
    2. Add the method didRegisterForRemoteNotificationsWithDeviceToken to Appdelegate.m to register the device and update its info on Pushbots server:
       
  •             Objective-C        
  •             Swift        
       
       
- (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken {
   // This method will be called everytime you open the app
   // Register the deviceToken on Pushbots
   [[Pushbots sharedInstance] registerOnPushbots:deviceToken];
}
-(void)application:(UIApplication *)application didFailToRegisterForRemoteNotificationsWithError:(NSError *)error{
   NSLog(@"Notification Registration Error %@", [error userInfo]);
}
       
           
   
    3. To handle the notification while the app is already open, add this method to Appdelegate:    
  •             Objective-C        
  •             Swift        
       
       
- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo {
   //Handle notification when the user click it while app is running in background or foreground.
   [[Pushbots sharedInstance] receivedPush:userInfo];
}
       
           
       
    4. You can Customize receivedPush method in Appdelegate, and handle notificaion payload [custom fields]:
-(void) receivedPush:(NSDictionary *)userInfo {
   //Try to get Notification from [didReceiveRemoteNotification] dictionary
   NSDictionary *pushNotification = [userInfo objectForKey:@"aps"];
   
   if(!pushNotification) {
       //Try as launchOptions dictionary
       userInfo = [userInfo objectForKey:UIApplicationLaunchOptionsRemoteNotificationKey];
       pushNotification = [userInfo objectForKey:@"aps"];
   }
   
   if (!pushNotification)
       return;
   
   //Get notification payload data [Custom fields]
   
    //For example: get viewControllerIdentifer for deep linking
   NSString* notificationViewControllerIdentifer = [userInfo objectForKey:@"notification_identifier"];
   
    //Set the default viewController Identifer
   if(!notificationViewControllerIdentifer)
       notificationViewControllerIdentifer = @"home";
   
   UIAlertView *message =
   [[UIAlertView alloc] initWithTitle:@"Notification"
                        message:[pushNotification valueForKey:@"alert"]
                        delegate:self
                        cancelButtonTitle:nil
                        otherButtonTitles: @"OK",
    nil];
   
   [message show];
   return;
}

-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    NSString *title = [alertView buttonTitleAtIndex:buttonIndex];
    if([title isEqualToString:@"OK"])
    {
        [[Pushbots sharedInstance] OpenedNotification];
    }
}
    5. Build and run the app on your device [Push Notifications are not supported on the simulator].
               
   

No valid aps-environment entitlement found for application

    go to Targets > Build settings > Code Signing Identity
and make sure it's not automatic and set to the profile matching certificate linked to the application ID for example , if you've created an app on Pushbots with development certificate , then you've to choose the development profile under code signing identity.        
                               

Handling Custom Fields

    1- If application is open or in background. You can recieve your info through didReceiveRemoteNotification and will pass it to userInfo:    
- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo {
    //Handle notification when the user click it while app is running in background or foreground.
    [[Pushbots sharedInstance] receivedPush:userInfo];
}
    Now all payload are stored in userInfo, to get for example variable newsID, you can get it through:
NSString* value = [userInfo objectForKey@"newsID"];
    Now code will be:
- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo {
    //Handle notification when the user click it while app is running in background or foreground.
    [[Pushbots sharedInstance] receivedPush:userInfo];
    //Get Custom field data
    NSString* value = [userInfo objectForKey@"newsID"];
}

    2- If the user clicked the notification, you'll need to add this code in application:didFinishLaunchingWithOptions    
NSDictionary *pushDict = [launchOptions objectForKey:UIApplicationLaunchOptionsRemoteNotificationKey];

if(pushDict){
    NSString* value = [pushDict objectForKey@"newsID"];
}

Debugging the library

    You can turn on Pushbots debugging by adding the following Preprocessor Macros in Build Settings: PUSHBOTS_DEBUG=1 and PUSHBOTS_ERROR=1.
    And to track info Add PUSHBOTS_INFO=1.

Sandbox

To set your device as testing device with Pushbots sanddbox feature, you can use this method:    
  •             Objective-C        
  •             Swift        
       
       
// Enable debug mode
[[Pushbots sharedInstance] debug:true];
       
           

Handling Badge

1 . to reset Bagde count .
   
  •             Objective-C        
  •             Swift        
       
       
// Reset badge on the server and in the app.
[[Pushbots sharedInstance] clearBadgeCount];
       
           
2 . to set Custom Bagde count:    
  •             Objective-C        
  •             Swift        
       
       
// Update badge count on the server and locally in the app.
[[Pushbots sharedInstance] setBadge:10];
       
           
3 . to decrease Badge count:    
  •             Objective-C        
  •             Swift        
       
       
// Decrease badge count by 2 on the server and locally.
[[Pushbots sharedInstance] decrementBadgeCountBy:2];
       
           

Other options

   
  •             Objective-C        
  •             Swift        
       
       
// Tag the device with "tag"
[[Pushbots sharedInstance] tag:@"tag"];
// unTag the device from "tag"
[[Pushbots sharedInstance] untag:@"tag"];
// Set device alias to "username"
[[Pushbots sharedInstance] setlias:@"username"];
// Update device Location <#(CLLocation *)#>
[[Pushbots sharedInstance] setLocation:<#(CLLocation *)#>];
       
           

Moving from Development to production

Now that you are done with testing push notifications with your iOS app and generated production certificate and uploaded it to PushBots. There are few other steps you need to review:
Make sure you’ve imported Apple Production iOS Push services: Bundle ID in keychain
After importing the production certificate, code signing identity/provisioning profile should be updated with iOS developer data:
  • Click on your project, below Targets click on your application title.
  • click on on Build settings.
  • Choose the production/adHoc provisioning profile.
  • Choose iPhone distribution as code signing identity.
After updating certificates you should reinstall the app on your device, in order to request a new token from Apple servers using the new certificate.
Also make sure Push Notification is enabled for AdHoc provisioning profile.