Welcome to ahex technologies

Send Pusuh Notifications To Adroid And IOS App [PART 1]

Send Push notification to the android and ios app[part-3]

Firebase Cloud Messaging Implementation for IOS 

Push notifications are apparently an essential thing in IOS Applications. It helps us gaining user retention, increasing active users, etc. To send a push notification to all our app users, we can use Firebase Cloud Messaging. We can send some promotional as well as regular information using Firebase Cloud Messaging (or FCM) very quickly .

In earlier blog ( Send Push Notification to Android and IOS APP [Part -1] /) we  understood about  Restful API implementation for Push Notification  using FCM and LARAVEL/PHP . Here we are going to consume those Restful api to  push notifications to iOS Apps.

Firebase Cloud Messaging ? 

Firebase Cloud Messaging (FCM) is a cross-platform messaging solution that lets you reliably deliver message at no cost. So it is free at the same time easy to use.

Push Notifications  allow developers to reach users and perform small tasks even when users aren’t actively using an app.

Push Notifications on the other hand are not scheduled by the app. They are triggered by another service  most often web server, and they are usually targeting to multiple devices simultaneously.With Push notifications, web server can send messages to users when necessary, either in random times or scheduled and either with a customised or default message body. In simple words, the life cycle of a remote notification can be summed up as shown

Why Push Notifications ? 

It’s quite often necessary to pull the user’s attention when an app is not running, and that’s possible to happen by using what we know as notifications.

Push Notification will be something looks like be

Steps to Integrate the Push Notifications in IOS Project. 

  1. The Certificate Signing Request.
  2. Create APP ID.
  3. Configure the app id for push notifications.
  4. Register your Device.
  5. Creating a Provisional profile for Development and Production.
  6. Configure the Project.
  7. Register for Push Notifications.
  8. Sending Push Notifications in sandbox mode.

Before we are going to start, make sure you create a new Xcode Project probably a single view application (in my case my Project name is Push Notifications Demo)

Once u have created the Push Notifications Demo Project, Put it aside for a few minutes, we will get back to it later.

Step 1 : Creating the CSR (Certificate Signing Request) file in your MAC. 

Now we will create a CSR file that we’ll use later on to create SSL Certificate for Push Notifications .

a) Search for KeyChain Access mac app in your system, once you get there, open

KeychainAccess –> Certificate Assistant –> Request a Certificate From a Certificate Authority,  as shown below

Creating CSR FILE

b) Once u click on Request a Certificate from a Certificate Authority a new window that comes up, Now u need to enter your details manually (like User Email Address, Common Name Fields ) and click on Saved to disk option, so you are able to save the CSR file to disk(save the file to desktop), and use it for later.  I have left the default file name for the CSR file.

After you see the message indicating the creation of your certificate request to disk, click “Done,” and you are ready to create the CSR File.

Step 2 : Creating the APP ID.

Our next step is to create a new APP ID in Apple Developer Website (developer.apple.com)

App ID is something which uniquely identify our app amongst others, and it will help APN Server to properly route the notifications.

a) First thing, login with your credentials in (developer.apple.com)

b) Click on Certificates, IDs and Profiles on the left side , a new window appears

c) You will see Identifiers on the left side column , click on APP IDs

d) let’s click to the plus button existing in the top-right side

It’s time now to Register a new APP ID for our demo application.

You can see App ID Description, App ID Prefix, App ID Suffix and App Services.

For APP ID Description, you can give it as per your app name (Push Notifications Demo). It’s not really important what you will enter here.

App ID Prefix : Usually you don’t really need to change the default value.

App ID Suffix :  Select Explicit APP ID

it is necessary when you’re about to enable push notification . Enter the app Bundle ID (you can find the bundle in our Xcode Project(Push Notifications Demo APP) which we have created  earlier).

App Services : 

At the bottom of the Provided Services, you will find the Push Notifications Option, click the checkbox to mark it as Selected. (Make sure Twice that it checked before you continue), this selection is going to play a huge role for showing up a push notifications in your iOS app.

Click Continue button, wait for a confirmation page to show up. Verify everything is okay, and then click to the submit button to get finished.

Now you can see the new APP ID (which we have created) being listed to the App ID’s Column.

Step 3 : Configure the APP ID for Push Notifications. 

Note : In this Step, we will be using the CSR file which we have created in the Step 1 .

If you notice clearly in the previous step,  even though we have enabled the push notifications service during APP ID Creation, it was showing configurable (actually it should be as Enabled).

We need to do some more actions, in order to switch to the proper state (which is Enabled).

Lets get going to the APP ID Section, Search for you APP ID which we have created in the above step.

Click on the app id it should expand it , right after all the displayed Services there is button named Edit. Click it to Proceed.

In the next step,  scroll down until you see the Push Notifications Section . You will find two buttons there which you can use to create SSL Certificates for both the Development and Production Stage.

As we are interested in the Development mode only, click to the first button as shown below. If you are really interested for Production mode you can go further to do that also.

Screen Shot 2018-02-10 at 2.38.48 PM

Its time now to make use of the Certificate Signing Request(CSR) file we created through Key chain Access app a couple of steps ago. If u remember clearly we have saved the file in the desktop of you mac with .csr file.

Now click on Create Certificate, 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 some instructions on how to generate the CSR file. As we have already created the CSR file in step 1 , so don’t worry about it .

Next, click to the Choose File button, now search for the CSR file (named CertificateSignningRequest.certSigningRequest if u haven’t changed the default CSR file name while Creation) in the desktop

Finally, click to the Generate blue color button, as shown below .

Screen Shot 2018-02-10 at 3.00.41 PM

Now you have created a new certificate that will enable you to send Push Notifications in the development mode.

You need to download it and add it to the keychain access.

Once you click on the download button , the file named aps_development.cer file  saved to your Downloads folder.

Note :  Double click on the aps_development.cer file, by doing this we are making sure that it is available in our keychain access app.

Its time now to check our certificate in Key chain access app

a) open key chain access app, click on login on left side of Keychain column .

b)click on Certificates on the left side of Category Column

Once you locate the new certificate which we have created just now(Apple Development IOS Push Services : com.ahextechnologies.PushNotificationsDemo something like this make sure to check yours) in the keychain access, right click on it and then click to the Export Apple Development IOS app Push Services Option .

Make sure that the .P12 file format is selected before you click to the save button. Save the certificate to the Desktop .

Once you click on save button, a pop up appear similar to below image asking you to enter the password, for now leave empty fields and click on OK button .

Screen Shot 2018-02-10 at 3.28.55 PM

Note : In this step we are not going to use the .p12 file you just exported to the desktop . You are going to need it, however in case you want to test push notifications from a server like Parse or Firebase or any backend team, where you have to Provide the .p12 file before even sending the first Push Notification .

Step 4 : Register Your Device with Apple Developer account. 

Initially you need to register you UDID in apple developer account in order to test push notifications .

Each iPhone device has a unique Device Identifier (UDID) which is a sequence of 40 letters and number that is specific to your device.It is like a serial number but much harder to guess . It look something like this (2a6f0aa904d137be2e1530235f5664094b831166).

  1. To get UDID, you have to plug your iPhone into a mac machine, wait until iTunes launches.
  2. In the left side , locate the information about you iPhone, including iPhone name, capacity, Software version etc .
  3. Click on phone symbol, on top left corner, there you will find the serial number, once you click on that serial number, it reveals the UDID. Copy it .

Now head back to apple developer website, Click to the All option under Devices Category. To add a new device, click to the button with Plus icon (+) to the top-right side.

  1. Enter your iPhone name
  2. Paste the UDID, which we have copied from iTunes account .

Click Continue, and in the next step make sure that information you just provided is correct . Once your are done, click to the Register button. Now u have successfully added your device UDID .

Step 5 : Creating Provisional Profile for Development

Let’s Create the Provisioning Profile for Development .

Note : If you want to upload the app to the App Store or either Test on TestFlight, you have to create a Distribution Provisioning Profile.

On the apple developer account, click to the Development in the Provisioning Profiles Category.

To Create a new Provisional Profile, click to the Plus button to the top-right side of the window.

Select the IOS App Development option (first one) by clicking on it .

Note : If you want to create for Distribution, select an option from second lower section (Most probably to the App Store.)

Screen Shot 2018-02-10 at 4.15.19 PM

For now we are selecting the iOS App Development .

Once you select the proper option, use the continue button to move to the next step.

Now we need to assign the app id which we had created earlier (In Step 1)

Next, you must include your IOS Development Certificate to the provisioning profile (supposing that you have at least one).If you have more than one certificate , and unsure which one you should select, then simply check the Select All checkbox and continue and get ready to select the device or devices that the app is going to be run to. Make sure to select your device UDID in which you want to test push notifications. once again, click Continue the you are ready

At last, give a name to your Provisioning Profile . I named it as “PNDemo Development Profile“, but feel free to give any other name you desire.

Click Generate and wait for the next screen. Once it is ready, you will be able to download .

If you named it just like i did, the your file is called PNDemo_Development_Profile.mobileprovision.

Note: Double click to the file you just downloaded , so as to be installed in you keychain access.

Step 6 : Configure the Project . 

From now onwards, we are not going to use apple developer website, we are going to focus on our Xcode Project.

There are two steps mainly we need to focus in our Xcode Project .

  1. Initially, we must enable Push Notifications capability in the our Xcode project, so we can get notifications on any device.
  2. Setting up the values for both code signing and Provisioning profiles that must be used by the app.

Note : Whatever we’re about to do regards only the Development mode, as we’re not dealing with Production stage at all. However, everything is quite similar in both cases, so you can easily follow the steps for Distribution mode in a real app before it goes live.

open our Xcode Project and select the project in project navigator . Make sure that you are in General tab, next you have to go to Team section 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. Please make sure to provide correct Apple ID and Password matching to your Developer account, and click to the Add button to get finished.

After you have successfully added your Apple ID, close the preferences window and return to General tab so you select the proper team name  . Check the image below .

Screen Shot 2018-02-14 at 7.27.16 AM

Next, click to the Capabilities tab and go to the Push Notifications Section . All you have to do here is just turn the Switch on. Check the image below .

Screen Shot 2018-02-14 at 7.27.44 AM

By enabling the Push Notifications capability, the proper entitlement is automatically added to the Project Navigator . Check the image below .

Screen Shot 2018-02-14 at 7.44.44 AM

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 the Automatic values 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 the 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 Provisoining Profile you will find the Code Signing Identity entry. 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 App Developer (iPhone Developer) value in the Debug

row and select Proper Identity .

Do not forget that your identity matching to Distribution should be set in the Release row in a real app as well.

Now click to the Target to left side of 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 proper Code Signing Identity.

Step 7: Register For Push Notifications through Firebase Console . 

Note : We need an IOS Device and apple developer account (Paid one). Push notification won’t be working on IOS Simulator.

Before writing some line of code, we need to install Firebase SDK in our IOS App through cocoa pods/manual way.

Open Safari/Chrome browser navigate to  ( https://console.firebase.google.com ), login with your any email account.

Once you login, you will see a message saying Welcome to Firebase!

Below that you have Recent Projects, Click on Add Project. Something like this.

eee

Once you click on Add Project, you will see a pop up with some other screen, something like below image.

Screen Shot 2018-02-15 at 6.59.59 AM

Enter your project name (in our case Push Notifications Demo) , Project ID default one don’t change it, Country/region in my case i kept it as United States, up next click on Create Project . Once u click on Create Project you will see the below image . Click on Continue .

Screen Shot 2018-02-15 at 7.00.38 AM

Once you click on Continue , you will be navigated to Firebase Dashboard Page. Which looks something like this :

Screen Shot 2018-02-15 at 7.06.48 AM

From above image click on IOS (Add Firebase to your iOS app). you will see a pop up asking us to enter BundleID, App NickName, App Store ID.

Screen Shot 2018-02-15 at 7.15.00 AM

Enter your Bundle ID (you can get bundle ID from our Xcode Project in our case my bundle ID is com.ahextechnologies.Push-Notifications-Demo). Press REGISTER APP.

Once you click on REGISTER APP , you will be navigated to below screen where you need to download the GoogleService-Info.plist file and drag and drop to your Xcode Project .

Screen Shot 2018-02-15 at 7.17.00 AM

Note: If u have Previously downloaded any GoogleServices-Info.plist file in your mac, make sure to delete those. Because when ur downloading the plist file from firebase it should be something like this (GoogleService-Info.plist). Don’t Change the Default name .

Screen Shot 2018-02-15 at 7.44.36 AM

Once you click on Continue from FIREBASE Console after downloading the Config.plist file in our Xcode Project . You will proceeded to the next screen.

Screen Shot 2018-02-15 at 7.56.17 AM

Make sure your mac machine is installed with cocoapods .

  1. Go to terminal, navigate to the project path(Push Notification Demo in our case).
  2. pod init
  3. open -a Xcode Podfile
  4. Place these two pod files :   pod ‘Firebase/Core’     pod ‘Firebase/Messaging’ 
  5. save the two pod files
  6. pod install

These will install your pod files in our Project. From now onwards open PushNotificationsDemo.XCWorkspace project .

Click on continue and change your app delegate.m file like below .

code

By adding [FIRApp configure] we are able connect to Firebase, when app enters into didFinishLaunchingWithOptions method .

import three header files in your app delegate.m file . change your app delegate.m file like this .

#import "AppDelegate.h"

#import <FirebaseAnalytics/FirebaseAnalytics.h>

#import <UserNotifications/UserNotifications.h>

#import <FirebaseMessaging/FirebaseMessaging.h>

@import Firebase;

@interface AppDelegate () <FIRMessagingDelegate>

{

}

@end

@implementation AppDelegate

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

{

     UIUserNotificationType allNotificationTypes =

    (UIUserNotificationTypeSound | UIUserNotificationTypeAlert | UIUserNotificationTypeBadge);

    UIUserNotificationSettings *settings =

    [UIUserNotificationSettings settingsForTypes:allNotificationTypes categories:nil];

    [[UIApplication sharedApplication] registerUserNotificationSettings:settings];

    [[UIApplication sharedApplication] registerForRemoteNotifications];



    [FIRApp configure];

    [FIRMessaging messaging].delegate = self;

    return YES;

}

// Once your are connected to Firebase , you will get FCM Token. 

- (void)messaging:(FIRMessaging *)messaging didReceiveRegistrationToken:(NSString *)fcmToken {



    NSLog(@"FCM registration token new one is : %@", fcmToken);

    [[NSUserDefaults standardUserDefaults]setObject:fcmToken forKey:@"FCMToken"];

    [[NSUserDefaults standardUserDefaults]synchronize];

    // TODO: If necessary send token to application server.

    // Note: This callback is fired at each app startup and whenever a new token is generated.

}

//This Method handles Push Notification when App is in Foreground ..!

- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo

fetchCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler {

    [[FIRMessaging messaging] appDidReceiveMessage:userInfo];

    NSDictionary *apsDict = [userInfo objectForKey:@"aps"];

    NSString *alertForegroundMessage = [NSString stringWithFormat:@"%@", [apsDict objectForKey:@"alert"]];

    NSLog(@"didReceiveRemoteNotification fetchCompletionHandler");

}

// Testing the PushNotification in Sandbox Mode. 

- (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken {

    NSString *fcmToken = [FIRMessaging messaging].FCMToken;

    NSLog(@"FCM registration token : %@", fcmToken);


    //    [[FIRInstanceID instanceID] setAPNSToken:deviceToken type:FIRInstanceIDAPNSTokenTypeProd];

        //NSLog(@"deviceToken1 = %@",deviceToken);


 [[FIRInstanceID instanceID] setAPNSToken:deviceToken type:FIRInstanceIDAPNSTokenTypeSandbox];

    NSString * deviceTokenString = [[[[deviceToken description]

                                      stringByReplacingOccurrencesOfString: @"<" withString: @""]

                                     stringByReplacingOccurrencesOfString: @">" withString: @""]

                                    stringByReplacingOccurrencesOfString: @" " withString: @""];

    NSLog(@"The generated device token string is : %@",deviceTokenString);

}

If your submitting the app to store, make sure you use this line of code in the above method .

NOTE :  [[FIRInstanceID instanceID] setAPNSToken:deviceToken type:FIRInstanceIDAPNSTokenTypeProd];   for Production .

 FIRInstanceIDAPNSTokenTypeSandbox for testing in sandbox mode/ Development mode .

- (void)tokenRefreshNotification:(NSNotification *)notification {


    InstanceID = [NSString stringWithFormat:@"%@",[notification object]];

    [self connectToFcm];

}

- (void)connectToFcm {

    NSLog(@"Connect to FCM is Called !");

    [[FIRMessaging messaging] connectWithCompletion:^(NSError * _Nullable error) {

        if (error != nil)

        {

            // NSLog(@"Unable to connect to FCM. %@", error);

        }

        else

        {

        }

    }];

}

UPLOADING .P12 CERTIFICATE IN FIREBASE CONSOLE 

Before that navigate to ( https://console.firebase.google.com )

Once you navigate to our Firebase console, we need to upload our certificates

  1. Click on Settings icon on left side of Project Overview .

project seting

2. Now click on Project Settings from the Pop Up . You will be presented with the below image.

general

3. Now click on CLOUD MESSAGING, there you will find two Sections  a)Project Credentials b) IOS App Configuration. scroll down you will find IOS App Configuration also, as below shown image.

bundleid

Select your appropriate bundle_id on left side, now you will see APNs Authentication Key and APNs Certificates we are dealing with APNs Certificates, In my case i am uploading Development p12 file.

We have already Created Development p12 file in step 3.

NOTE : If you are shipping your app to store, make sure you upload Production_Development_Certificate.p12 .

Once you click on UPLOAD from Development APNs certificate you will be pop up with image below .

upload developmt

Attach the related .p12_certificate and in step 3 we haven’t given the password, so left the password field as blank and click on upload .

Now its time to test the Push Notification from Firebase console .

TESTING NOTIFICATION FROM FIREBASE CONSOLE 

Click on Grow from left side column .

Once you click on Grow, you will find Predictions, Notifications etc ..

Click on Notifications, then click on SEND YOUR FIRST MESSAGE

send first message

Once you click on SEND YOUR FIRST MESSAGE, you will be navigated to this screen

compose nil

Enter the message text, message label as you wish. For Delivery date select Send Now and in Target select User segment

select your bundle id from the drop down in Target User if ..

compose not nil

Once you have selected your respective bundle_id(in my case it is  com.ahextechnologies.Push-Notifications-Demo) press Send Message .

once you have click on send Message, you will receive the push notifications in your app.

Before that when you launch the app in your testing device, you will ask to click on ok or Dont’allow the push notifications. Make sure to click ok from the below image. Then only you will receive the Push Notification.

Note : Make sure to keep the app in background and test the notification.

TESTING NOTIFICATION USING FCM TOKEN FROM FIREBASE CONSOLE. 

Note: If you want to test the push notification for single device, you need to place the FCM TOKEN in Firebase console .

Select the single device from the image below .

Make sure to place the FCM Token which you have received in appdelegate.m file .

Once you click on SEND MESSAGE, you will be able to get the Push Notification to the desired FCM TOKEN User mobile.

Note : I have shared my appdelegate.m file in above steps, in which you will be able to get the FCM Token .

TESTING NOTIFICATION FROM SERVER. 

After setting up the server side like we explained in the last tutorial, just send the FCM token of the device to server where you want to see the notification .

Navigate back to Xcode.

Change the code in ViewController.m file as below

@interface ViewController () {

 NSString *FCMTokenString;

 NSDictionary *postDic;

}

#pragma mark - ViewDidLoad

- (void)viewDidLoad {

    FCMTokenString = [defaults objectForKey:@"FCMToken"];

// I have saved the FCM token which i have got in appdelegate.m file, i am retrieving it in the variable called FCMTokenString.

   [self performSelector:@selector(ServiceCallForFCMToken) withObject:nil afterDelay:0.1];

}

#pragma mark - Implementation of Service Call For FCM Token.

-(Void)ServiceCallForFCMToken {

      postDic = @{

                        @"device_type":@"ios",

                        @"token":FCMTokenString

                    };

 NSError *error = nil;

  NSData *jsondata = [NSJSONSerialization dataWithJSONObject:postDic

                                                       options:NSJSONWritingPrettyPrinted

                                                         error:&error];

    NSMutableURLRequest * request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:URL_TO_SEND_FCM_TOKEN]    cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:120.0];


    [request setValue:@"application/json" forHTTPHeaderField:@"Content-type"];

    [request setValue:@"application/json" forHTTPHeaderField:@"Accept"];

    [request setHTTPMethod:@"POST"];

    [request setValue:[NSString stringWithFormat:@"%lu", (unsigned long)[jsondata length]] forHTTPHeaderField:@"Content-Length"];

    [request setHTTPBody:jsondata];


    NSHTTPURLResponse *responseCode = nil;

    NSData *oResponseData = [NSURLConnection sendSynchronousRequest:request returningResponse:&responseCode error:&error];

    NSLog(@"The response from server is %@", error);

    NSString *responseData;

    if([responseCode statusCode] != 200)

    {

        NSLog(@"Error getting %ld, HTTP status code ", (long)[responseCode statusCode]);

        NSLog(@"Val of %ld error in ViewController is:%@",(long)[responseCode statusCode],error);

    }

    else

    {

        responseData = [[NSString alloc] initWithData:oResponseData encoding:NSUTF8StringEncoding];

    }


    NSString *resultValue = [NSString stringWithFormat:@"%@", responseData];

    NSLog (@"The Final response of FCM URL_TO_SEND_FCM_TOKEN is %@", resultValue);

    NSError * err;

    NSData *data =[resultValue dataUsingEncoding:NSUTF8StringEncoding];

    NSDictionary * response;

    response = (NSDictionary *)[NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:&err];

    NSLog(@"The final response error is %@", error);

// Once you get the response from the server saying that FCM Token added successfully/ Success message, that it . You are done sending the token to Server.

}

After successful request for sending FCM token to server, whenever there is a notification posted from server you should see the notification in the device like above.