Sunday, July 31, 2016

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 = [UNUserNotificationCenter currentNotificationCenter];
    [center requestAuthorizationWithOptions:(UNAuthorizationOptionBadge | UNAuthorizationOptionSound | UNAuthorizationOptionAlert)
                          completionHandler:^(BOOL granted, NSError * _Nullable error) {
                              if (!error) {
                                  NSLog(@"request authorization succeeded!");
                                  [self showAlert];
                              }
                          }];

-(void)showAlert {
    UIAlertController *objAlertController = [UIAlertController alertControllerWithTitle:@"Alert" message:@"show an alert!" preferredStyle:UIAlertControllerStyleAlert];
    
    UIAlertAction *cancelAction = [UIAlertAction
                                   actionWithTitle:@"OK"
                                   style:UIAlertActionStyleCancel
                                   handler:^(UIAlertAction *action) {
                                       NSLog(@"Ok clicked!");
                                   }];
    [objAlertController addAction:cancelAction];
    
    
    [[[[[UIApplication sharedApplication] windows] objectAtIndex:0] rootViewController] presentViewController:objAlertController animated:YES completion:^{
        
    }];
    
}

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

 UNMutableNotificationContent *objNotificationContent = [[UNMutableNotificationContent alloc] init];
    objNotificationContent.title = [NSString localizedUserNotificationStringForKey:@“Notification!” arguments:nil];
    objNotificationContent.body = [NSString localizedUserNotificationStringForKey:@“This is local notification message!“
                                                         arguments:nil];
    objNotificationContent.sound = [UNNotificationSound defaultSound];
    
    /// 4. update application icon badge number
    objNotificationContent.badge = @([[UIApplication sharedApplication] applicationIconBadgeNumber] + 1);
    
    // Deliver the notification in five seconds.
    UNTimeIntervalNotificationTrigger *trigger = [UNTimeIntervalNotificationTrigger
                                                  triggerWithTimeInterval:10.f repeats:NO];       
    
    UNNotificationRequest *request = [UNNotificationRequest requestWithIdentifier:@“ten”
                                                                          content:objNotificationContent trigger:trigger];
    /// 3. schedule localNotification
    UNUserNotificationCenter *center = [UNUserNotificationCenter currentNotificationCenter];
    [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)

11 comments:

  1. how can i trigger Localnotification on scheduled date using datepicker. means user set notification via datepicker.

    ReplyDelete
  2. i tried abv sample but it is not firing on scheduled tym it is firing only once?

    ReplyDelete
  3. thanks, it is helpfull for me but in ios10 timeinterval must be 60 if i used repeats:true which am i getting from complier side but here i want to reduce timeinterval .so pls tell me what can i do for it.

    ReplyDelete
  4. wondered upon your blog and wanted to say that I have really enjoyed reading your blog posts. Any way I’ll be subscribing to your feed and I hope you post again soon.

    iOS Training in Chennai
    Android Training in Chennai
    php Training in Chennai

    ReplyDelete
  5. Pretty article! I found some useful information in your blog, it was awesome to read, thanks for sharing this great content to my vision, keep sharing..

    Mobile App Development Company in Chennai
    Android app Development Company in Chennai
    ios app development Company in Chennai

    ReplyDelete
  6. to add an attachment (like image) use this code
    objNotificationContent.sound = [UNNotificationSound defaultSound]; // after this

    NSString *UNExtensionID=@"animatedContentExtension";
    NSError *error;
    UNNotificationAttachment *attachment;
    //Image adding
    NSURL *url = [[NSBundle mainBundle] URLForResource:@"ur image name" withExtension:@"extension of image"];

    attachment=[UNNotificationAttachment attachmentWithIdentifier:@"imageID"
    URL: url
    options:nil
    error:&error];
    objNotificationContent.attachments=@[attachment];
    objNotificationContent.categoryIdentifier= UNExtensionID;

    if no image is displaying then goto->target->buildPhases->copyB undle Resources-> add the file.
    clean project and run.

    ReplyDelete
  7. Thanks for posting useful information.You have provided an nice article, Thank you very much for this one. And i hope this will be useful for many people.. and i am waiting for your next post keep on updating these kinds of knowledgeable things...Really it was an awesome article...very interesting to read..
    please sharing like this information......
    Android training in chennai
    Ios training in chennai

    ReplyDelete
  8. Being new to the blogging world I feel like there is still so much to learn. Your tips helped to clarify a few things for me as well as giving..
    Android App Development Company

    ReplyDelete
  9. I wondered upon your blog and wanted to say that I have really enjoyed reading your blog posts. Any way I’ll be subscribing to your feed and I hope you post again soon.
    iOS App Development Company
    iOS App Development Company

    ReplyDelete
    Replies
    1. Really appreciate that you like it!
      Go through my StackOverFlow profile...you will find interesting Q&A all about iOS..

      Delete
  10. These ways are very simple and very much useful, as a beginner level these helped me a lot thanks fore sharing these kinds of useful and knowledgeable information.
    Fitness SMS
    Fitness Text
    Salon SMS
    Salon Text
    Investor Relation SMS
    Investor Relation Text
    Mobile Marketing Services
    mobile marketing companies
    Sms API

    ReplyDelete