Objective-C Programming Resources and Tutorials | Ahex https://ahex.co/category/objective-c/ Ahex Technologies focuses on offshore outsourcing, by providing innovative and quality services and value creation for our clients. Tue, 29 Aug 2023 08:10:39 +0000 en-US hourly 1 https://wordpress.org/?v=6.8.3 202019870 Google Sign in SDK integration for ios apps https://ahex.co/google-integration-ios/?utm_source=rss&utm_medium=rss&utm_campaign=google-integration-ios Tue, 29 May 2018 07:35:54 +0000 http://ahex.wpenginepowered.com/?p=2286 Google plus login lets users login into your iOS app with their existing Google account and get their profile information like name, email and other details. By integrating google plus login in your apps, you can get all the user details in one shot. The major advantage of integrating G+ login is, you can drive...

The post Google Sign in SDK integration for ios apps appeared first on Welcome to Ahex Technologies.

]]>

Google plus login lets users login into your iOS app with their existing Google account and get their profile information like name, email and other details. By integrating google plus login in your apps, you can get all the user details in one shot. The major advantage of integrating G+ login is, you can drive more users to your app by providing quicker & easiest way of signup process.

So let’s start by doing required setup.

Step 1: Set up your CocoaPods dependencies

Google Sign-In uses CocoaPods to install and manage dependencies. Open a terminal window and navigate to the location of the Xcode project for your application. If you have not already created a Podfile for your application, create one now:

  1. Open your terminal and type CD “—project path—”
  2. Type “pod init” , now Podfile will be created in your project, and open that pod file by using command “open podfile
  3. Now in the podfile, type command like   pod ‘GoogleSignIn’  ” to install all requirement frameworks like “Google signIn”, “GoogleToolboxForMac”, “GTMOAuth2”, “GTMSessionFetcher”…etc

podInstallation

Now in Terminal,  while installing all above frameworks it will be looks like below screenshot.

podInstallation_2

This creates an .xcworkspace file for your application. Use this file for all future development on your application.

Step 2: Get Google Sign-in Client ID:

Google sign in Client ID is an ID that allows us to make calls to Google API within our iOS based application.

To get ClientID follow below steps:

  1. Sign into Google Developers Console with the help of your Google Account.
  2. If you have not created any app then create it. If created, then choose your app and add it to bundle identifier. Now choose your country and then click to continue Button to proceed ahead.
  3. Select the Google service that you want to make use of. Now, Select Google Sign-in & click -> ENABLE GOOGLE SIGN-IN to enable Google sign in service.
  4. Whenever you click on “Enable button”, it will sanction Google Sign in for your app.
  5. Whenever you enable Google Sign-in for your app, click -> Continue button that will generate configuration files for you.
  6. Now, you will be navigated to download the configuration file. Click -> Download GoogleService-info.plist button to download the configuration file. This file will be used for later purposes.

Now open downloaded plist .and it will be like the below screenshot.plist

Step 3: Add a URL scheme to your project:

Google Sign-in requires a custom URL Scheme to be added to your project. To add the custom scheme:

  1. Open your project configuration: double-click the project name in the left tree view. Select your app from the TARGETS section, then select the Info tab, and expand the URL Types section.
  2. Click the + button, and add your reversed client ID as a URL scheme.
    The reversed client ID is your client ID with the order of the dot-delimited fields reversed. For example you can check in above screenshot.
  3. When completed, your config should look something similar to the following (but with your application-specific values):

URLSchemes

4. Now that you’ve downloaded the project dependencies and configured your Xcode project, you can add Google Sign-In to your iOS app.

Step 4: Enable SignIn:

(A) To enable sign in, you must configure the GIDSignIn shared instance. You can do this in many places in your app. Often the easiest place to configure this instance is in your app delegate’s application:didFinishLaunchingWithOptions: method.

  1. In your app delegate’s .h file, declare that this class implements the GIDSignInDelegate protocol.

gidProtocol

(B) In your app delegate’s application:didFinishLaunchingWithOptions: method, configure the GIDSignIn shared instance and set the sign-in delegate.

didFinishLaunching

(C) Implement the application:openURL:options: method of your app delegate. The method should call the handleURL method of the GIDSignIn instance, which will properly handle the URL that your application receives at the end of the authentication process.

applicationOpenURL

(D) For your app to run on iOS 8 and older, also implement the deprecated application:openURL:sourceApplication:annotation: method.

- (BOOL)application:(UIApplication *)application
            openURL:(NSURL *)url
  sourceApplication:(NSString *)sourceApplication
         annotation:(id)annotation 
{
  return [[GIDSignIn sharedInstance] handleURL:url
                             sourceApplication:sourceApplication
                                    annotation:annotation];
}

(E) In the app delegate, implement the GIDSignInDelegate protocol to handle the sign-in process by defining the following methods which are showing in below screenshot.

Our Services are Mean Stack Development | Mern Stack Development

AppDelegate

Step 5: Add the sign-in button

Next, you will add the Google Sign-In button so that the user can initiate the sign-in process. Make the following changes to the view controller that manages your app’s sign-in screen:

(A) In the App Delegate.h file, add the Google Sign-In interface and declare that this class implements the GIDSignInUIDelegate protocol.

In ViewController.h file copy below this.

viewController

(B) In the view controller., override the viewDidLoad method to set the UI delegate of the GIDSignIn object, and (optionally) to sign in silently when possible.

viewController(m)

(C) In these examples, the view controller is a subclass of UIViewController. If in your project, the class that implements GIDSignInUIDelegate is not a subclass of UIViewController, implement the signInWillDispatch:error:, signIn:presentViewController:, and signIn:dismissViewController: methods of the GIDSignInUIDelegate protocol. For example you can add below code .

viewController(m)_1

(D) Add a GIDSignInButton to your storyboard, XIB file, or instantiate it programmatically. To add the button to your storyboard or XIB file, add a View and set its custom class to GIDSignInButton.

Storyboard

(E) If you want to customize the button, do the following:

    • In your view controller’s .h file, declare the sign-in button as a property.
      @property(weak, nonatomic) IBOutlet GIDSignInButton *signInButton;
    • Connect the button to the signInButton property you just declared.
    • Customize the button by setting the properties of the GIDSignInButton object.

Step 6: Sign out the user

You can use the SignOut method of the GIDSignIn object to sign out your user on the current device, for example:

In ViewController.h, copy below code:

- (IBAction)didTapSignOut:(id)sender 
{
  [[GIDSignIn sharedInstance] signOut];
}

Step 7: Retrieving user information

Once the user has authenticated and authorized access to the scopes you request, you can access user information through the GIDGoogleUser object.

Copy Below Code in ViewController.m class :

viewController(m)_2

Now Run your application and Click on Login button on simulator, it will be redirected to the gmail sign in page, there you have to enter email id and password, and these credentials will be secured and this screen something looks like below screenshots.

googleSignIn

After submission of your credentials click on “NEXT” button and now the new page will be opened with a title of accounts.google.com and this page will asks you like “are you want to access your google account?” And stating with your email id. Now below in this page you can see two buttons as CANCEL and ALLOW.

Now Click on ALLOW, and again you will be redirected to another screen where you will find all the details of your google account such as name email id, phone number , date of birth..etc.

googleSignIn_2

You can get your client ID, UserId, Full Name, Email ID..etc in your console.. the same I am showing in simulator for your reference.

google_SignIn_3

The post Google Sign in SDK integration for ios apps appeared first on Welcome to Ahex Technologies.

]]>
2286
Facebook login for iOS Apps https://ahex.co/login-with-facebook/?utm_source=rss&utm_medium=rss&utm_campaign=login-with-facebook Sat, 28 Apr 2018 14:14:16 +0000 http://ahex.wpenginepowered.com/?p=2216 Introduction Now a days we are using lots of web and mobile applications. Each application requires email and password for logging in and using the full feature of application. With so many web/app accounts, the users struggle with remembering a strong password for all of their web/app accounts. So to reduce the burden of remembering...

The post Facebook login for iOS Apps appeared first on Welcome to Ahex Technologies.

]]>
Introduction

Now a days we are using lots of web and mobile applications. Each application requires email and password for logging in and using the full feature of application.

With so many web/app accounts, the users struggle with remembering a strong password for all of their web/app accounts.

So to reduce the burden of remembering these many passwords, the developers got a clean and easy way for this sign in process. That is Social login.

Social login, provides users with one single login using an account they already have on different social networks like Facebook, Google+, Twitter etc. By using their Facebook, Twitter or Google+ account, users do not generate a new password or create a new account on a third-party website. Instead, they just use their social network login information.

There are several benefits of social login to users and developers. In this post I am going to explain how to Facebook login.

Advantages of using social login are :

  1. The biggest advantage is not having to build or implement your own authentication service.
  2. It gives users a simple, fast, and secure way to login to your app.  No need for them to remember another username/password combination.
  3. Authenticity. For example, news websites have seen the quality of their article comments improve dramatically after implementing Facebook Login.  No more trolling.

Is “login with Facebook” secure in an app? 

Yes, it is completely secure because when you are using Facebook to login to some app , you are actually logging in to Facebook. Once your credentials are verified by Facebook server, you are redirected to the app meaning that login attempt was successful. Same happens with every other login that asks you to login via Google or some other account. So it is completely secure to login with Facebook.

Let’s talk about procedures for implementing login with Facebook.

How to implement Login with Facebook in your app?

    1. Setting an App or Create a New App :

Go to this link https://developers.facebook.com/docs/facebook-login/ios here you need to create AppId. There you will get option between Search for your app or Create a New App. 

SelectApp

Click on Create a New App. Add your display name and click on Create App ID.

AppId  

2. Setup Development Environment :

Now for setting up development environment, best way is to use CocoaPods. Using CocoaPods

           a.) Navigate to your project folder in terminal.

           b.) Type the below commands

$ sudo gem install cocoapods
$ pod init $ open Podfile

           Now in the Podfile paste pod ‘FBSDKLoginKit’ above “end” and save the Podfile.

$ pod install

Screen Shot 2018-05-26 at 2.17.02 PM

After this come back to Facebook developers account and register Bundle ID of your app.

3. Register and configure your app with Facebook :

You need to register your bundel identifier (Bundle ID). In the box add Bundle ID from your app. Make Enable Single Sign-On YES.

BundleId

4. Configure info.plist :

Most important is to configure info.plist file. Right-click info.plist, and choose Open As Source Code. On developers account you will be getting few lines of code to paste in info.plist file. Paste that code between <dict>…</dict>. Best is paste just above </dict>. e.g. snippet will look like below

Info  

5. Connect Your App Delegate :

Add the following code in your AppDelegate directly.

AppDelegate

#import <FBSDKCoreKit/FBSDKCoreKit.h>

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

  [[FBSDKApplicationDelegate sharedInstance] application:application didFinishLaunchingWithOptions:launchOptions];

  // Add any custom logic here.

  return YES;

}


- (BOOL)application:(UIApplication *)application openURL:(NSURL *)url options:(NSDictionary<UIApplicationOpenURLOptionsKey,id> *)options {

  BOOL handled = [[FBSDKApplicationDelegate sharedInstance] application:application openURL:url sourceApplication:options[UIApplicationOpenURLOptionsSourceApplicationKey] annotation:options[UIApplicationOpenURLOptionsAnnotationKey]
  ];

  // Add any custom logic here.

  return handled;

}

   

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
  
  [[FBSDKApplicationDelegate sharedInstance] application:application didFinishLaunchingWithOptions:launchOptions];

  // Add any custom logic here.

  return YES;

}


- (BOOL)application:(UIApplication *)application openURL:(NSURL *)url options:(NSDictionary<UIApplicationOpenURLOptionsKey,id> *)options {

  BOOL handled = [[FBSDKApplicationDelegate sharedInstance] application:application openURL:url sourceApplication:options[UIApplicationOpenURLOptionsSourceApplicationKey] annotation:options[UIApplicationOpenURLOptionsAnnotationKey]
  ];

  // Add any custom logic here.

  return handled;

}

    

// Below is required when iOS version is less than iOS 10

- (BOOL)application:(UIApplication *)application openURL:(NSURL *)url sourceApplication:(NSString *)sourceApplication annotation:(id)annotation {

  BOOL handled = [[FBSDKApplicationDelegate sharedInstance] application:application openURL:url sourceApplication:sourceApplication annotation:annotation
  ];

  // Add any custom logic here.

  return handled;

}     

6. Add Facebook Login to Your Code :

In your view controller add the following code

//  ViewController.m

//  LoginWithFacebookDemo

//

//  Created by Admin on 28/04/18.

//  Copyright © 2018 Ahex Technologies. All rights reserved.

//

#import "ViewController.h"
#import <FBSDKCoreKit/FBSDKCoreKit.h>
#import <FBSDKLoginKit/FBSDKLoginKit.h>
#import "SecondViewController.h"
#import "ModelClass.h"

@interface ViewController () {
    CGRect rect;
}
@end


@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];

    rect = [[UIScreen mainScreen] bounds];

    UIButton *facebookButton = [[UIButton alloc]initWithFrame:CGRectMake(12, rect.size.height-60-24, rect.size.width-24, 60)];
    facebookButton.layer.cornerRadius = 5.0;
    [facebookButton setBackgroundColor:[UIColor blueColor]];
    [facebookButton addTarget:self action:@selector(facebookButtonAction) forControlEvents:UIControlEventTouchUpInside];
    [facebookButton setTitle:@"Login With Facebook " forState:UIControlStateNormal];
    [facebookButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [self.view addSubview:facebookButton];    

}

-(void)facebookButtonAction {

    if ([FBSDKAccessToken currentAccessToken]) {
        // User is logged in, do work such as go to next view controller.        
        NSLog(@"Current Token Value:%@",FBSDKAccessToken.currentAccessToken);

        SecondViewController *settings_obj = [[UIStoryboard storyboardWithName:@"Main" bundle:nil]instantiateViewControllerWithIdentifier:@"SecondViewController"];
        [self.navigationController pushViewController:settings_obj animated:YES];

    }
    else
    {
        //  Take user to login with facebook page

        FBSDKLoginManager *login = [[FBSDKLoginManager alloc] init];
        [login

         logInWithReadPermissions: @[@"public_profile", @"email", @"user_friends"]
         fromViewController:self
         handler:^(FBSDKLoginManagerLoginResult *result, NSError *error) {

             if (error)
             {
                 //NSLog(@"Process error");
             }
             else if (result.isCancelled)
             {
                 //NSLog(@"Cancelled");
             }
             else
             {
                 NSMutableDictionary* parameters = [NSMutableDictionary dictionary];
                 [parameters setValue:@"email,first_name,last_name,picture.type(large),gender,verified,id" forKey:@"fields"];


                 [[[FBSDKGraphRequest alloc] initWithGraphPath:@"me" parameters:parameters]
                  startWithCompletionHandler:^(FBSDKGraphRequestConnection *connection,
                                               id result, NSError *error) {

                      if (!error)
                      {
                          NSLog(@"Value of result is:%@",result);

                          NSString *emailObject = [NSString stringWithFormat:@"%@", [result objectForKey:@"email"]];
                          NSString *idObject = [NSString stringWithFormat:@"%@", [result objectForKey:@"id"]];
                          NSString *firstNameObject = [NSString stringWithFormat:@"%@", [result objectForKey:@"first_name"]];
                          NSString *lastNameObject = [NSString stringWithFormat:@"%@", [result objectForKey:@"last_name"]];
                          NSString *gender = [NSString stringWithFormat:@"%@", [result objectForKey:@"gender"]];
                          NSString *verifiedObject =@"true";

                          NSDictionary *fbDict = @{
                                           @"verified":verifiedObject,
                                           @"fb_user_id":idObject,
                                           @"first_name":firstNameObject,
                                           @"last_name":lastNameObject,
                                           @"gender":gender,
                                           @"email":emailObject
                                           };

                          NSLog(@"Value of facebookDict is:%@",fbDict);
                          ModelClass.sharedInstance.userProfileDictionary = fbDict;

                      }

                  }]; // parameters

                 SecondViewController *svc = [[UIStoryboard storyboardWithName:@"Main" bundle:nil]instantiateViewControllerWithIdentifier:@"SecondViewController"];
                 [self.navigationController pushViewController:svc animated:YES];

             }// else

         }]; // login

    } // else

}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];

    // Dispose of any resources that can be recreated.
}

@end 

7. Remove the Facebook access token :

For Log out you need to add the following code to the logout button

Put below code in SecondViewController.h

@interface SecondViewController : UIViewController

- (IBAction)logoutAction:(UIButton *)sender;
@property (strong,nonatomic) NSDictionary *userDataDict;
@property (strong, nonatomic) IBOutlet UILabel *dictionaryLabel;

@end

Put below code in SecondViewController.m


//  SecondViewController.m
//  LoginWithFacebookDemo
//
//  Created by Admin on 28/04/18.
//  Copyright © 2018 Ahex Technologies. All rights reserved.
//

#import "SecondViewController.h"
#import <FBSDKLoginKit/FBSDKLoginKit.h>
#import "ModelClass.h"

@interface SecondViewController ()

@end

@implementation SecondViewController

- (void)viewDidLoad {

    [super viewDidLoad];

    _userDataDict = ModelClass.sharedInstance.userProfileDictionary;
    _dictionaryLabel.text = [NSString stringWithFormat:@"%@",_userDataDict];

    // Do any additional setup after loading the view.
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];

    // Dispose of any resources that can be recreated.
}


- (IBAction)logoutAction:(UIButton *)sender {

    FBSDKLoginManager *login = [[FBSDKLoginManager alloc] init];
    [login logOut];
    

    UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"Success" message:@"logged out successfully" preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction *okAction = [UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleDefault handler:^(UIAlertAction * action)
                               {
                                   // Ok action example
                                   [self.navigationController popViewControllerAnimated:YES];
                               }];

    UIAlertAction *otherAction = [UIAlertAction actionWithTitle:@"Cancel" style:UIAlertActionStyleDefault handler:^(UIAlertAction * action)
                                  {
                                      // Other action
                                      //[self.navigationController popViewControllerAnimated:YES];
                                  }];

    [alert addAction:okAction];
    [alert addAction:otherAction];
    [self presentViewController:alert animated:YES completion:nil];

}

@end

8.Modal Class :

I have used modal class for storing the dictionary of user information and displaying it in SecondViewController.

ModelClass.h

//  ModelClass.h

//  ModelDemo

//

//  Created by admin on 20/04/18.

//  Copyright © 2018 Ahex Technologies. All rights reserved.

//

#import <Foundation/Foundation.h>

@interface ModelClass : NSObject

@property (strong, nonatomic) NSDictionary *userProfileDictionary;
+ (instancetype)sharedInstance;

@end

ModelClass.m

//

//  ModelClass.m

//  ModelDemo

//

//  Created by admin on 20/04/18.

//  Copyright © 2018 Ahex Technologies. All rights reserved.

//

#import "ModelClass.h"

@implementation ModelClass

-(instancetype)init {

    self=[super init];
    if (self)
    {
        
    }
    return self;
}

+ (instancetype)sharedInstance {
    static ModelClass *sharedInstance = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{

        sharedInstance = [[ModelClass alloc] init];

        // Do any other initialisation stuff here
    });
    return sharedInstance;
}

@end

Summary

So here we can see how easily we can integrate Facebook login feature to our app. Also it will reduce the burden of creating your own login and authentication system. We could easily authenticate the user and allow them to use the great features provided by our app. 

If this article is helpful then do share. If you want some more information or feel any difficulty while integrating Facebook login, please tell in comment. And feedbacks are always welcome.


The post Facebook login for iOS Apps appeared first on Welcome to Ahex Technologies.

]]>
2216
Send Pusuh Notifications To Adroid And IOS App [PART 1] https://ahex.co/send-push-notification-to-android-and-ios-app-part-1/?utm_source=rss&utm_medium=rss&utm_campaign=send-push-notification-to-android-and-ios-app-part-1 Mon, 26 Feb 2018 04:15:03 +0000 http://ahex.wpenginepowered.com/?p=2101 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...

The post Send Pusuh Notifications To Adroid And IOS App [PART 1] appeared first on Welcome to Ahex Technologies.

]]>
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.

The post Send Pusuh Notifications To Adroid And IOS App [PART 1] appeared first on Welcome to Ahex Technologies.

]]>
2101