Wednesday, 15 June 2016

Push Notification

PUSH NOTIFICATION






Step 1: The Certificate Signing Request
Now that you have created the demo project, put it aside for a few minutes, and get ready for the first step in the whole preparation process. Here, we are going to produce a Certificate Signing Request (CSR) file that we’ll use later on to create a SSL certificate for push notifications.
For this step you’ll need the Keychain Access Mac app, so either use the Launchpad or the Spotlight search to find it and open it. If you’re new to Keychain Access, make sure you don’t delete any existing stuff accidentally.
Once you get there, open the Keychain Access > Certificate Assistant > Request a Certificate From a Certificate Authority… menu, as shown next:


In the window that comes up, you need to mandatorily fill in the User Email Address and Common Name fields. Besides that, click to the Saved to disk option so you are able to save the CSR file to disk, and use it later in the Apple Developer website.




Click Continue and optionally choose a folder and a name for the CSR file right before you save it. I have created a folder to keep together all the files we’re about to produce in this tutorial (called PNDemo Files, I encourage you to do the same), and I’ve left the default file name for the CSR file.
Once you see a message saying that your certificate request has been created on disk, click Done and you’re… done. The certificate we just requested for and saved to disk will be used to sign other certificates in the Apple Developer website.

Step 2: Create an App ID

Our next step is to create a new App ID in the Apple Developer website. This App ID is going to uniquely identify our app amongst others, and it will help APN servers to properly route the notifications. Actually, as you’ll see next, we’ll connect the App ID to a couple of other things: To a new certificate for push notifications, and to a provisioning profile that will let us run the app on a test device.
First things first, so begin by going to the Apple Developer Member Center. Provide your credentials, and get connected. Then, click to the Certificates, Identifiers & Profiles link, so you’re navigated to the proper page.



By landing to the new webpage, click to the Identifiers link under the iOS Appssection:


You’ll see that the App IDs option is pre-selected (in the Identifiers category to the left menu), and a list with all the existing App ID values is shown to the main window area. The new App ID that we’re about to create is going to be added to that list, but first, let’s click to the plus button existing in the top-right side:


It’s time now to configure a new App ID for our demo application. For starters, we need to fill in two fields:
  1. A description about the new App ID. In this sample it’s not really important what you will type here, but you’d better pick a good and precise description in real-world cases.
  2. The Bundle ID of the app. Just copy that value from your Xcode project, and paste it here.
As you can see, there’s also one more value between the above two. It’s the App ID Prefix, and usually you don’t really need to change the default value. However, don’t hesitate to do so if it’s necessary to pick a different prefix value. For the purpose of this tutorial, I just leave the default value.


There’s an important detail you should keep in mind: Setting an explicit App IDis necessary when you’re about to enable push notifications, as the App ID must match to specific app Bundle ID. Using a wildcard App ID (an App ID ending with an asterisk *) is something that you’re not allowed to do in this case. Personally, I always find it way better to set an explicit App ID than using the wildcard, no matter what the features of the app are meant to be. Doing that, it’s also easy to distinguish each App ID when you see it listed in the IDs summary page.
After having set the above values, scroll down until you reach the App Servicesarea. At the bottom of the provided services, you’ll find the Push Notificationsoption. Click to the checkbox to mark it as selected, and make sure twice that it is checked before you continue.



Next, click to the Continue button, and wait for a confirmation page to show up. Verify that everything is okay, and then click to the Submit button to get finished. If you feel that something is wrong, then you can go back and change any of the previously set values.



The last step here is to see the Registration Complete page. Just click to the Donebutton, and you’ll see the new App ID being listed to the App IDs collection.



Step 3: Configure the App ID for Push Notifications
You might have noticed in the previous part that the status for both Development and Distribution mode is not marked as Enabled but as Configurable, even though we checked (enabled) the Push Notifications service during the App ID creation. That means that we need to take some extra actions so we can manage to switch to the proper state.



Note that for the sake of the tutorial we’ll configure the push notifications for the Development mode only. As we are not going to test any push notifications in production stage, we won’t touch the Distribution mode at all. However, whatever you’ll see next applies for that case as well. In a real app you should definitely configure the Distribution mode, otherwise push notifications are not going to work when your app will go live to the App Store.
Let’s get going now by clicking to the newly created App ID in the list so it gets expanded. Right after all the displayed services there’s a button titled Edit. Click it to proceed.
In the next step scroll down until you see the Push Notifications section. You’ll find two buttons there which you can use to create SSL Certificates for both the Development and Production stage. As we’re interested in the Development mode only, click to the first button as shown below:



It’s about time now to make use of the Certificate Signing Request file we created through the Keychain Access app a couple of parts ago. So, let’s keep going with that process, and in the first step of the guide just click to the Continue button. Here you get just some instructions on how to generate the CSR, in case you haven’t done so already.



Next, click to the Choose File… button so you can search for the CSR file that you generated in the first step. If you hadn’t changed the default file name, then you’re looking for a file titledCertificateSigningRequest.certSigningRequest.
Finally, click to the Generate blue button that you can see in the following screenshot.



Great, you just created a new certificate that will enable you to send push notifications in development (sandbox) mode. Now, you must download it and add it to the keychain (the Keychain Access app on Mac), so proceed by clicking to the Download button.




The file you just downloaded is named aps_development.cer. Spot it in your Downloads folder and double click on it, so it’s added to the collection of certificates in the Keychain Access app.



An important notice: When the Keychain Access app opens by double clicking to the .cer file, make sure that the new certificate is added to the login keychain, and not to the System or any other keychain. If that happens, then just drag and drop the certificate to the login keychain. That’s important for what we’ll do right next.





Once you locate the new certificate in the Keychain, right click on it, and then click to the Export “…” option.





Make sure that the .p12 file format is selected before you click to the Save button.





You can skip setting a password simply by clicking to the OK button in the next window. If you set one, make sure to remember it or write it somewhere, because the file becomes unusable if you forget it.





Note that in this tutorial we are not going to use the file you just exported. You are going to need it, however, in case you want to test push notifications from a server like Parse, where you have to provide the .p12 file before even sending your first notification. So for now just keep that file along with the rest. At this point it’s important to realise that knowing how to generate a .p12 file for development mode enables you to do the same for the production stage as well.

Step 4: Register Your Device

First of all, let me say that this step is useful for testing push notification only (in sandbox mode), and it’s not necessary for the production mode. Here we are going to register the device (or devices) that the app is going to be tested to in the Apple Developer website. If you have already done so in the past and your device is already listed there, then you can just skip this step.
Supposing that you are going to add your device for first time here, what you have to initially do is to plug it to your Mac and then go to Xcode. Open theWindow > Devices menu, so a new window with all devices and simulators to appear.
Continue by clicking to your device to the left, so you see its details on the main window area. You’ll notice that there is a field called Identifier, containing a long string with letters and digits as its value. Double click on that value, and then copy it.






Now go back to the Apple Developer website, and click to the All option under theDevices category. Any existing registered devices will be listed to the main window area. To add a new device, click to the button with the plus icon (+) to the top-right side.
In the new form that appears, first set a name for your device in the Name field (for example, Gabriel’s iPhone 6S, or My lovely iPad). Then, paste the device identifier you copied before in the UDID field, and you’re done.







Click Continue, and in the next step make sure that the information you just provided is accurate. Once you are ready, click to the Register button to get finished with the guide.
You can verify that your device has been added indeed to the list with the registered devices simply by clicking once again to the All option in the Devicescategory. Go through all entries until you find the one with the name you just entered.

Step 5: Create a Provisioning Profile for Development

As a last job in the Apple Developer website, let’s create a provisioning profile for Development so we can code sign our app later on. Note that you have to create a Distribution provisioning profile and use it similarly to what you’ll learn here, prior to uploading your app to iTunesConnect either for use on TestFlight or on the App Store.
On the Apple Developer page, click to the Development link in the Provisioning Profiles category. Any existing profiles will be shown to the main window side, and in a few minutes our new one will be added there as well.
To create a new provisioning profile, click to the plus (+) button to the top-right side of the window. In the new form that appears, and for the sake of our example, select the iOS App Development option (the first one) by clicking on it. Note that you have to select an option from the second (lower) section (most probably the App Store) when you’ll be creating a provisioning profile for Distribution.
Anyway, once you select the proper option, use the Continue button to move to the next step.






Now it’s time to connect the profile we’re creating to the App ID matching to our app. Locate and select the proper App ID value in the dropdown control and then move on.






Next, you must include your iOS Development certificate to the provisioning profile (supposing that you have at least one). If there are more than one certificates like it’s shown in the screenshot below and you are unsure which one you should select, then simply check the Select All checkbox and you are covered.




Continue, and get ready to select the device or devices that the app is going to be run to. Make sure that you won’t forget to select any devices which you want to test push notifications to. Once again, click Continue when you’re ready.

Lastly, give a name to your provisioning profile so you can distinguish it amongst others. I named it “PNDemo Development Profile“, but feel free to give any other name you desire.


Click Generate and wait for the next screen. When the new profile gets ready, you’ll be able to download it as shown next:




All you have to do now is to follow the instructions of the above image, and double click to the file you just downloaded so as to be installed. If you named it just like I did, then your file is calledPNDemo_Development_Profile.mobileprovision.

Step 6: Configure the Project

Starting from this part, we’re going to abandon the Apple Developer website, and to focus on our project. We have two goals to achieve here:
  1. Initially, we must enable the Push Notifications capability in the project, so we can actually get notifications on any device. This step is basic, but trust me, even though it is a simple prerequisite, a lot of developers simply forget to turn a simple switch on and activate that capability.
  2. We’ll properly set the values for both code signing and provisioning profiles that must be used by the app. Please note that whatever we’re about to do regards only the Development mode, as we’re not dealing with the Production stage at all. However, everything is quite similar in both cases, so you can easily follow the same steps for the Distribution mode in a real app before it goes live.
So, bring the app in Xcode in front of you and select the project in the Project Navigator. Make sure that you are in the General tab. What you have to do is to go to the Team dropdown control, and select the proper team that will be used for provisioning.



If you see no entries in the Team, then you must go to Xcode > Preferences…menu, in the Accounts tab and add a new Apple ID. Provide the Apple ID and password matching to your Developer account, and click to the Add button to get finished. Going into the details of this process is out of our scope, therefore if you are unsure on what you should do please take a look at this link for a step by step guide. After you have successfully added your Apple ID, close the Preferences window and return to General tab so you select the proper team value.
Next, click to the Capabilities tab and go to the Push Notifications section. All you have to do here is to just turn the switch on.




As the message in the above screenshot says, by enabling the Push Notifications capability the proper entitlement is automatically added to the Info.plist file.
Now open the Build Settings tab, and locate the Code Signing section. Expand the Provisioning Profile entry, and in the row titled Debug click to theAutomatic value so as to display a list with all the existing provisioning profiles in your Developer account. Select the one with the name matching to the profile you downloaded and installed in the previous step.




There is no need to set a provisioning profile in the Release row right now, as we haven’t created one for Distribution. However, you mandatorily have to do that in the same fashion when you create and download the proper provisioning profile from the Apple Developer website.
Right above the Provisioning Profile you will find the Code Signing Identityentry. Click to the arrow in the left side to expand it, if it’s not already expanded. Similarly to what we just did, click to the iOS Developer (or iPhone Developer)value in the Debug row, and select a proper identity as shown next:




Do not forget that your identity matching to Distribution should be set in theRelease row in a real app as well.
Now click to the Target to the left side of the General tab, and select the Project:




Go to the Code Signing section, and follow the exact same steps as above. First select the correct provisioning profile for the Debug mode, and then the properCode Signing Identity.




Step 7: Register for Push Notifications

Coding Part :-

AppDelegate.m


- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions

{

            // ****************  Apple Push Integration Starts Here    **************** //
    // ---------------------------------------------------------------------- //
    
    /// New iOS 8 User Notification Settings
    
    NSDictionary *userInfo = [launchOptionsobjectForKey:UIApplicationLaunchOptionsRemoteNotificationKey];
    
    if (userInfo != NULL)
    {
        [[UIApplication sharedApplicationsetApplicationIconBadgeNumber:0];
        
        NSString *notification = [[userInfo valueForKey:@"aps"valueForKey:@"alert"];
        
        NSLog(@"%@", notification);
    }
    
#if __IPHONE_OS_VERSION_MAX_ALLOWED >= 80000
    if ([application respondsToSelector:@selector(registerUserNotificationSettings:)])
    {
        UIUserNotificationType userNotificationTypes = (UIUserNotificationTypeAlert |
                                                        UIUserNotificationTypeBadge |
                                                        UIUserNotificationTypeSound);
        UIUserNotificationSettings *settings = [UIUserNotificationSettingssettingsForTypes:userNotificationTypes
                                                                                 categories:nil];
        [application registerUserNotificationSettings:settings];
        // [application registerForRemoteNotifications];
    }
    else
#endif
    {
        // iOS 7
        /*
         [application registerForRemoteNotificationTypes:(UIRemoteNotificationTypeBadge |
         UIRemoteNotificationTypeAlert |
         UIRemoteNotificationTypeSound)];
         */
    }
    
    // ---------------------------------------------------------------------- //
    

    //-------
    return YES;

}


#pragma mark -Push Notification

- (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken
{
    NSLog(@"tk : %@" , deviceToken) ;
}

- (void)application:(UIApplication *)application didRegisterUserNotificationSettings:(UIUserNotificationSettings *)notificationSettings
{
    [application registerForRemoteNotifications];
}

- (void)application:(UIApplication *)application didFailToRegisterForRemoteNotificationsWithError:(NSError *)error
{
    //  NSLog(@"Did Fail to Register for Remote Notifications");
    NSLog(@"%@, %@", error, error.localizedDescription);
}

- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo
{
    [[UIApplication sharedApplicationsetApplicationIconBadgeNumber:0];
    
    NSString *notification = [[userInfo valueForKey:@"aps"valueForKey:@"alert"];
    
    NSLog(@"%@",notification);

}







//----------------------------------------------- For ios 10 -----------------------------------------------//
//-----------------------------------------------
//-----------------------------------------------
//-----------------------------------------------



For iOS 10 using xCode 8 GM.

1) In the targets, under Capabilities enable Push Notifications to add Push Notifications Entitlements.
2) Implement UserNotifications.framework into your app. Import UserNotifications.framework in your AppDelegate.
#import <UserNotifications/UserNotifications.h>
@interface AppDelegate : UIResponder   <UIApplicationDelegate,UNUserNotificationCenterDelegate>

@end
3) In didFinishLaunchingWithOptions method assign UIUserNotificationSettings and implement UNUserNotificationCenter delegate.
#define SYSTEM_VERSION_GRATERTHAN_OR_EQUALTO(v)  ([[[UIDevice currentDevice] systemVersion] compare:v options:NSNumericSearch] != NSOrderedAscending)

-(BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions{

if(SYSTEM_VERSION_GRATERTHAN_OR_EQUALTO(@"10.0")){
    UNUserNotificationCenter *center = [UNUserNotificationCenter currentNotificationCenter];
    center.delegate = self;
    [center requestAuthorizationWithOptions:(UNAuthorizationOptionSound | UNAuthorizationOptionAlert | UNAuthorizationOptionBadge) completionHandler:^(BOOL granted, NSError * _Nullable error){
         if( !error ){
             [[UIApplication sharedApplication] registerForRemoteNotifications];
         }
     }];  
}

return YES;
}
4) Now finally implement this two delegate methods.
//====================For iOS 10====================

-(void)userNotificationCenter:(UNUserNotificationCenter *)center willPresentNotification:(UNNotification *)notification withCompletionHandler:(void (^)(UNNotificationPresentationOptions options))completionHandler{

    //Called when a notification is delivered to a foreground app. 

    NSLog(@"Userinfo %@",notification.request.content.userInfo);

    completionHandler(UNNotificationPresentationOptionAlert);
}

-(void)userNotificationCenter:(UNUserNotificationCenter *)center didReceiveNotificationResponse:(UNNotificationResponse *)response withCompletionHandler:(void(^)())completionHandler{

   //Called to let your app know which action was selected by the user for a given notification.

   NSLog(@"Userinfo %@",response.notification.request.content.userInfo);

}
















No comments:

Post a Comment