Local Notification in iOS 10 for Objective-C and Swift 3

The way you use to work with Local Notification in iOS 9 and below is completely different in iOS 10.

Below screen grab from Apple release notes depicts this.


Below is code for local notification :

Objective-C :

1. In App-delegate.h file use @import UserNotifications;

2. App-delegate should conform to UNUserNotificationCenterDelegate protocol

3. In didFinishLaunchingOptions use below code :

 UNUserNotificationCenter *center = [UNUserNotificationCentercurrentNotificationCenter];
    [center requestAuthorizationWithOptions:(UNAuthorizationOptionBadge | UNAuthorizationOptionSound | UNAuthorizationOptionAlert)
                          completionHandler:^(BOOL granted, NSError * _Nullable error) {
                              if (!error) {
                                  NSLog(@"request authorization succeeded!");
                                  [self showAlert];
                              }
                          }];

-(void)showAlert {
    UIAlertController *objAlertController = [UIAlertControlleralertControllerWithTitle:@"Alert" message:@"show an alert!"preferredStyle:UIAlertControllerStyleAlert];
    
    UIAlertAction *cancelAction = [UIAlertAction
                                   actionWithTitle:@"OK"
                                   style:UIAlertActionStyleCancel
                                   handler:^(UIAlertAction *action) {
                                       NSLog(@"Ok clicked!");
                                   }];
    [objAlertController addAction:cancelAction];
    
    
    [[[[[UIApplication sharedApplicationwindowsobjectAtIndex:0rootViewControllerpresentViewController:objAlertController animated:YEScompletion:^{
        
    }];
    
}


4. Now create a button in any view controller and in IBAction use below code :

 UNMutableNotificationContent *objNotificationContent = [[UNMutableNotificationContent allocinit];
    objNotificationContent.title = [NSStringlocalizedUserNotificationStringForKey:@“Notification!”arguments:nil];
    objNotificationContent.body = [NSStringlocalizedUserNotificationStringForKey:@“This is local notification message!“
                                                         arguments:nil];
    objNotificationContent.sound = [UNNotificationSounddefaultSound];
    
    /// 4. update application icon badge number
    objNotificationContent.badge = @([[UIApplicationsharedApplicationapplicationIconBadgeNumber] + 1);
    
    // Deliver the notification in five seconds.
    UNTimeIntervalNotificationTrigger *trigger = [UNTimeIntervalNotificationTrigger
                                                  triggerWithTimeInterval:60.f repeats:NO];       
    
    UNNotificationRequest *request = [UNNotificationRequestrequestWithIdentifier:@“ten”
                                                                          content:objNotificationContent trigger:trigger];
    /// 3. schedule localNotification
    UNUserNotificationCenter *center = [UNUserNotificationCentercurrentNotificationCenter];
    [center addNotificationRequest:request withCompletionHandler:^(NSError * _Nullable error) {
        if (!error) {
            NSLog(@“Local Notification succeeded“);
        }
else {
    NSLog(@“Local Notification failed“);
}
    }];








Swift 3:

1. In App-delegate.h file use import UserNotifications

2. App-delegate should conform to UNUserNotificationCenterDelegate protocol

3. In didFinishLaunchingWithOptions use below code 

 // Override point for customization after application launch.
        let center = UNUserNotificationCenter.current()
        center.requestAuthorization(options: [.alert, .sound]) { (granted, error) in
            // Enable or disable features based on authorization.
            if((error == nil)) {
                print(“Request authorization failed!")
            }
            else {
                print(“Request authorization succeeded!")
                self.showAlert()
            }
        }


func showAlert() {
        let objAlert = UIAlertController(title: "Alert", message: "Request authorization succeeded", preferredStyle: UIAlertControllerStyle.alert)
        
        objAlert.addAction(UIAlertAction(title: "OK", style: UIAlertActionStyle.default, handler: nil))
        //self.presentViewController(objAlert, animated: true, completion: nil)
        
        UIApplication.shared().keyWindow?.rootViewController?.present(objAlert, animated: true, completion: nil)
    }



4. Now create a button in any view controller and in IBAction use below code :

let content = UNMutableNotificationContent()
        content.title = NSString.localizedUserNotificationString(forKey: "Hello!", arguments: nil)
        content.body = NSString.localizedUserNotificationString(forKey: "Hello_message_body", arguments: nil)
        content.sound = UNNotificationSound.default()
        content.categoryIdentifier = "notify-test"
        
        let trigger = UNTimeIntervalNotificationTrigger.init(timeInterval: 5, repeats: false)
        let request = UNNotificationRequest.init(identifier: "notify-test", content: content, trigger: trigger)
        
        let center = UNUserNotificationCenter.current()
        center.add(request)



Comments

Post a Comment

Popular posts from this blog

iOS Architecture

Performance Tips for IOS Application

setNeedsLayout vs layoutIfNeeded Explained