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

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 = { ...

What are the Alternatives of device UDID in iOS? - iOS7 / iOS 6 / iOS 5 – Get Device Unique Identifier UDID

Get Device Unique Identifier UDID Following code will help you to get the unique-device-identifier known as UDID. No matter what iOS user is using, you can get the UDID of the current iOS device by following code. - ( NSString *)UDID { NSString *uuidString = nil ; // get os version NSUInteger currentOSVersion = [[[[[UIDevice currentDevice ] systemVersion ] componentsSeparatedByString: @" . " ] objectAtIndex: 0 ] integerValue ]; if (currentOSVersion <= 5 ) { if ([[ NSUserDefaults standardUserDefaults ] valueForKey: @" udid " ]) { uuidString = [[ NSUserDefaults standardDefaults ] valueForKey: @" udid " ]; } else { CFUUIDRef uuidRef = CFUUIDCreate ( kCFAllocatorDefault ); uuidString = ( NSString *) CFBridgingRelease ( CFUUIDCreateString ( NULL ,uuidRef)); CFRelease (uuidRef); [[ NSUserDefaults standardUserDefaults ] setObject: uuidString ForKey: @" udid " ]; [[ NSUserDefaults standardUserDefaults ] synchro...

An introduction to Size Classes for Xcode 8

Introduction to Size Classes for Xcode In iOS 8, Apple introduced  size classes , a way to describe any device in any orientation. Size classes rely heavily on auto layout. Until iOS 8, you could escape auto layout. IN iOS8, Apple changed several UIKit classes to depend on size classes. Modal views, popovers, split views, and image assets directly use size classes to determine how to display an image. Identical code to present a popover on an iPad  causes a iPhone to present a modal view. Different Size Classes There are two sizes for size classes:  compact , and  regular . Sometime you’ll hear about any.  Any  is the generic size that works with anything. The default Xcode layout, is  width:any height:any . This layout is for all cases. The Horizontal and vertical dimensions are called  traits , and can be accessed in code from an instance of  UITraitCollection . The  compact  size descr...