Skip to main content

How To Use Push Notification In IOS 10 In Objective C

Push Notification

Use the UserNotifications.framework to add Linker Library framework.

#import <UserNotifications/UserNotifications.h>

Set Delegate <UNUserNotificationCenterDelegate>

#define SYSTEM_VERSION_GRATERTHAN_OR_EQUALTO(v)([[[UIDevice currentDevice] systemVersion] compare:v options:NSNumericSearch]!= NSOrderedAscending)

AppDelegate.m

didFinishLaunchingWithOptions

// Register for Remote Notifications
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];
              }
       }];
 } else {
           // Code for older versions
           [application registerForRemoteNotificationTypes:(UIRemoteNotificationTypeAlert |                                                 UIRemoteNotificationTypeBadge | UIRemoteNotificationTypeSound)];
}

// And add this method to AppDelegate.m For IOS < 10

- (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken
{
     NSLog(@"Did Register for Remote Notifications with Device Token (%@)", deviceToken);
     NSString *token = [[deviceToken description] stringByTrimmingCharactersInSet:                                                              [NSCharacterSet characterSetWithCharactersInString:@"<>"]];
     NSLog(@"content---%@", token);
     [[NSUserDefaults standardUserDefaults] setObject:token forKey:@"Devicetoken"];
     [[NSUserDefaults standardUserDefaults]synchronize];
 NSString *savedValue = [[NSUserDefaults standardUserDefaults]stringForKey:@"Devicetoken"];
    NSLog(@"%@",savedValue);
}

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

// And add this method to AppDelegate.m For IOS > 10

- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo fetchCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler
{
    NSLog(@"info %@",userInfo);
    NSString *message = [[userInfo objectForKey:@"aps"] valueForKey:@"alert"];
    NSLog(@"Message : %@",message);
    UIApplicationState state = [[UIApplication sharedApplication] applicationState];
    [[UIApplication sharedApplication] setApplicationIconBadgeNumber: 0];
    [[UIApplication sharedApplication] cancelAllLocalNotifications];

    if (state == UIApplicationStateActive) {

    /// if test ios < 10
    if (SYSTEM_VERSION_GRATERTHAN_OR_EQUALTO(@"10.0")) 
    {
       completionHandler(UNAuthorizationOptionSound | UNAuthorizationOptionAlert |                               UNAuthorizationOptionBadge);
       NSLog(@"info %@",userInfo);
} else {
      /// Custom Push Notification
      completionHandler(UNAuthorizationOptionSound | UNAuthorizationOptionNone |                                UNAuthorizationOptionBadge);
      NSLog(@"info %@",userInfo);
     }
} else {
     completionHandler(UNAuthorizationOptionSound | UNAuthorizationOptionAlert |                              UNAuthorizationOptionBadge);
   }
}

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

-(void)userNotificationCenter:(UNUserNotificationCenter *)center willPresentNotification:(UNNotification *)notification withCompletionHandler:(void (^)(UNNotificationPresentationOptions options))completionHandler
{
    NSLog(@"User Info : %@",notification.request.content.userInfo);
    NSString *message = [[notification.request.content.userInfo objectForKey:@"aps"]                                                                    valueForKey:@"alert"];
    NSLog(@"Message : %@",message);
    UIApplicationState state = [[UIApplication sharedApplication] applicationState];
    [[UIApplication sharedApplication] setApplicationIconBadgeNumber: 0];
    [[UIApplication sharedApplication] cancelAllLocalNotifications];

    if (state == UIApplicationStateActive) 
    {
        /// if test ios < 10
        if(SYSTEM_VERSION_GRATERTHAN_OR_EQUALTO(@"10.0")) {

             completionHandler(UNAuthorizationOptionSound | UNAuthorizationOptionAlert |                                UNAuthorizationOptionBadge);
   } else {
          /// Custom Push Notification
        completionHandler(UNAuthorizationOptionSound | UNAuthorizationOptionNone |                                UNAuthorizationOptionBadge);
    }
} else {
       completionHandler(UNAuthorizationOptionSound | UNAuthorizationOptionAlert |                               UNAuthorizationOptionBadge);
   }
}

-(void)userNotificationCenter:(UNUserNotificationCenter *)center didReceiveNotificationResponse:(UNNotificationResponse *)response withCompletionHandler:(void(^)())completionHandler
{
   NSLog(@"User Info :%@",response.notification.request.content.userInfo);
   UIApplicationState state = [[UIApplication sharedApplication] applicationState];

  if (state == UIApplicationStateActive) 
  {}
} else {
     [PrefsUserDefaults setObject:@"YES" forKey:@"isNotification"];
     [PrefsUserDefaults synchronize];
}

 [[UIApplication sharedApplication] cancelAllLocalNotifications];
 [[UIApplication sharedApplication] setApplicationIconBadgeNumber: 0];

completionHandler();
}

/// And New How to create APNS certificates

1. Log in to the Apple Developer Program Portal, Account section.

2. Click on the Certificates, Identifiers & Profiles.

3. To mack a new App ID open the App IDs menu section and click on the + button.

4. Enter your App ID Description Name (1), Bundle ID (2).Ensure you use Explicit App ID option. Click Continue.

5. You should see now the info about App ID you are creating. Click Register button to finish.

Generating a Certificate Request

You must generate a certificate request file so that you can use it to request for a development SSL certificate later on.

 1. Launch the Keychain Access application in your macOS.

2. Select Keychain Access -> Certificate Assistant -> Request a Certificate From a Certificate Authority.

3. Enter the information required and check the Saved to disk option. Then click Continue button

4. Save the certificate request using the suggested name and click Save. Click Done in the next screen.

The same process above applies when generating the production certificate.

Configuring an App ID for Push Notifications

Once an App ID is created, you need to configure it for push notifications.

1. To configure an App ID for push notification, you need to select the App in the App IDs list. Under Application Services click on the Edit button for the selected App ID.

2. Configuration page will appear. Scroll down to Push Notifications section. Enable checkbox **
(1)** and click the Create Certificate (2) button:
       
3. A wizard will appear. Click Continue.

4. Click the Choose File button to locate the Certificate Request file that you have saved earlier (Generating a Certificate Request section). Click Generate.

5. Your SSL Certificate will now be generated. Now you can click Download to download your certificate.

Also, you can download new certificate in Application Services list.

The same process above applies when generating the production certificate.

Prepare APNS certificate

  1. The SSL Certificate that you download is named aps_developer_identity .cer. Double-click on it to install it into Keychain Access application. The SSL certificate will be used by QuickBlox application so that it can contact the APNs to send push notifications to your iOS application.

  2. Launch Keychain Access from your local Mac, then go to 'login' keychains and filter by the 'Certificates' category. You will see an expandable option called Apple Development iOS Push Services, paired with a private key.

3. Right-click on your new push certificate and choose Export "Apple Development iOS Push Services .... Save this as apns-dev-cert.p12 file somewhere you can access it.

Enter your usual admin password for your computer to confirm and finalise the export process.
                                 
The same process above applies when generating the production certificate.

Create provision profile

Provisioning is the process of preparing and configuring an app to launch on devices and to use app services. During development, you choose which devices can run your app and which app services your app can access. A provisioning profile is downloaded from your developer account and embedded in the app bundle, and the entire bundle is code-signed. The embedded provisioning profile is installed on the device before the app is launched. If the information in the provisioning profile doesn’t match certain criteria, your app won’t launch.

Log in to the Apple Developer Program Portal, Account section
Click on the Certificates, Identifiers & Profiles.

3. Open Provisioning Profiles menu section. Click on the + button.

4. Select a type of the provisioning profile you need to create (1) and click on 'Continue' button to continue the creation.
     
5. Select App ID you are creating the provisioning profile for.

6. Select the certificates you wish to include in this provisioning profile and click on 'Continue button'.
 
7. Select the devices you wish to include in this provisioning profile and click on 'Continue' button.
   
8. Input the Provisioning profile name and click on 'Generate' button to generate the profile.
   
9. Now you can download new Provision profile.
   
Also you can download this Provisioning profile later. Open a list with all Provisioning profiles and choose the required. Additional options become available.

 10. After click on 'Download' button the Provision profile will be downloaded to your hard disk. Double click on it to add to provisions library.
                       
Configuring your iOS App for Push Notifications

The first step is to change the App ID. Go to App Settings -> General and change Bundle Identifier to identifier that you type.

2. Then in the section named Singing (Debug or Release) select your Provision Profile.

3. Go to App Settings -> Capabilities and switch Push Notifications to On.

4. Now you can run your application and play with Push Notifications. Make sure you use real iOS device, because push notifications will not work on simulator.



Comments

Popular Posts

How I Reduced the Size of My React Native App by 85%

How and Why You Should Do It I borrowed 25$ from my friend to start a Play Store Developer account to put up my first app. I had already created the app, created the assets and published it in the store. Nobody wants to download a todo list app that costs 25mb of bandwidth and another 25 MB of storage space. So today I am going to share with you how I reduced the size of Tet from 25 MB to around 3.5 MB. Size Matters Like any beginner, I wrote my app using Expo, the awesome React Native platform that makes creating native apps a breeze. There is no native setup, you write javascript and Expo builds the binaries for you. I love everything about Expo except the size of the binaries. Each binary weighs around 25 MB regardless of your app. So the first thing I did was to migrate my existing Expo app to React Native. Migrating to React Native react-native init  a new project with the same name Copy the  source  files over from Expo project Install all de...

React Native - Text Input

In this chapter, we will show you how to work with  TextInput  elements in React Native. The Home component will import and render inputs. App.js import React from 'react' ; import Inputs from './inputs.js' const App = () => { return ( < Inputs /> ) } export default App Inputs We will define the initial state. After defining the initial state, we will create the  handleEmail  and the  handlePassword  functions. These functions are used for updating state. The  login()  function will just alert the current value of the state. We will also add some other properties to text inputs to disable auto capitalisation, remove the bottom border on Android devices and set a placeholder. inputs.js import React , { Component } from 'react' import { View , Text , TouchableOpacity , TextInput , StyleSheet } from 'react-native' class Inputs extends Component { state = { ...

How to recover data of your Android KeyStore?

These methods can save you by recovering Key Alias and Key Password and KeyStore Password. This dialog becomes trouble to you? You should always keep the keystore file safe as you will not be able to update your previously uploaded APKs on PlayStore. It always need same keystore file for every version releases. But it’s even worse when you have KeyStore file and you forget any credentials shown in above box. But Good thing is you can recover them with certain tricks [Yes, there are always ways]. So let’s get straight to those ways. 1. Check your log files → For  windows  users, Go to windows file explorer C://Users/your PC name/.AndroidStudio1.4 ( your android studio version )\system\log\idea.log.1 ( or any old log number ) Open your log file in Notepad++ or Any text editor, and search for: android.injected.signing and if you are lucky enough then you will start seeing these. Pandroid.injected.signing.store.file = This is  file path where t...