Add Local Notification in iOS 10 - Swift 3

51,760

Solution 1

You need to register for Notification...I tried and this works.

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
        // Override point for customization after application launch.
        let center = UNUserNotificationCenter.current()
        center.requestAuthorization([.alert, .sound]) { (granted, error) in
            // Enable or disable features based on authorization.
        }
        return true
    }

Edit: You dont need to put your app in background to present notification from iOS 10 onwards.

Use below callback to configure notification to present in foreground.

func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void)

Here is a sample project.

Solution 2

With Objective-C implemation:

I have wrote a Demo project here: iOS10AdaptationTips .

  1. import UserNotifications

    ///Notification become independent from Foundation
    @import UserNotifications;
    
  2. request authorization for localNotification

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

    Request Authorization: enter image description here

  3. schedule localNotification

  4. update application icon badge number

        //        //Deliver the notification at 08:30 everyday
        //        NSDateComponents *dateComponents = [[NSDateComponents alloc] init];
        //        dateComponents.hour = 8;
        //        dateComponents.minute = 30;
        //        UNCalendarNotificationTrigger *trigger = [UNCalendarNotificationTrigger triggerWithDateMatchingComponents:dateComponents repeats:YES];
    
        UNMutableNotificationContent *content = [[UNMutableNotificationContent alloc] init];
        content.title = [NSString localizedUserNotificationStringForKey:@"Elon said:" arguments:nil];
        content.body = [NSString localizedUserNotificationStringForKey:@"Hello Tom!Get up, let's play with Jerry!"
                                                             arguments:nil];
        content.sound = [UNNotificationSound defaultSound];
    
        /// 4. update application icon badge number
        content.badge = @([[UIApplication sharedApplication] applicationIconBadgeNumber] + 1);
        // Deliver the notification in five seconds.
        UNTimeIntervalNotificationTrigger *trigger = [UNTimeIntervalNotificationTrigger
                                                      triggerWithTimeInterval:5.f repeats:NO];
        UNNotificationRequest *request = [UNNotificationRequest requestWithIdentifier:@"FiveSecond"
                                                                              content:content trigger:trigger];
        /// 3. schedule localNotification
        UNUserNotificationCenter *center = [UNUserNotificationCenter currentNotificationCenter];
        [center addNotificationRequest:request withCompletionHandler:^(NSError * _Nullable error) {
            if (!error) {
                NSLog(@"add NotificationRequest succeeded!");
            }
        }];
    

then it will appear like this:

In Background : enter image description here Lock Screen:
enter image description here

If Repeat by default only show one enter image description here instead of show many on the lock screen on iOS9: enter image description here and also support 3D Touch automatically enter image description here

I write a Demo here: iOS10AdaptationTips .

Solution 3

Here are a few steps:

  1. Make sure you have the permission. If not, use UNUserNotificationCenter.current().requestAuthorization to get that. Or follow the answer if you want to show the request pop up more than once.

  2. If you want to show the notification foreground, having to assign UNUserNotificationCenterDelegate to somewhere.

  3. Show me the code

    @IBAction func sendPressed(_ sender: AnyObject) {
        let content = UNMutableNotificationContent()
        content.title = "Hello"
        content.body = "What up?"
        content.sound = UNNotificationSound.default()
    
        let trigger = UNTimeIntervalNotificationTrigger.init(timeInterval: 5, repeats: false)
        let request = UNNotificationRequest.init(identifier: "FiveSecond", content: content, trigger: trigger)
    
        let center = UNUserNotificationCenter.current()
        center.add(request) { (error) in
            print(error)
        }
    }
    
    override func viewDidLoad(_ animated: Bool) {
        super.viewDidLoad(animated)
    
        // Assign the delegate
        UNUserNotificationCenter.current().delegate = self
    
        // Ask the permission
        let center = UNUserNotificationCenter.current()
        center.requestAuthorization([.alert, .sound]) { (granted, error) in
            if granted {
                // do something
            }
        }
    }
    // Remember to add UNUserNotificationCenterDelegate to your view controller
    func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
        print("Got the msg...")
        completionHandler([.badge, .sound, .alert])
    }
    

Solution 4

I solved my problem as follows (Firebase, Swift 3):

Find this method on your AppDelegate:

func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {

Find this line:

completionHandler()

End set:

completionHandler([.alert,.sound,.badge])

notifications are not firing if you not pass your presentation options to completionHandler method.

Share:
51,760
Bjarte
Author by

Bjarte

Updated on July 09, 2022

Comments

  • Bjarte
    Bjarte almost 2 years

    So I been trying to add a notification to the new UNUserNotificationCenter, but I don't seem to get it.

    My view controller has an action:

    @IBAction func sendPressed(_ sender: AnyObject) {
        let content = UNMutableNotificationContent()
    
        content.title = "Hello"
        content.body = "What up?"
        content.sound = UNNotificationSound.default()
    
        // Deliver the notification in five seconds.
        let trigger = UNTimeIntervalNotificationTrigger.init(timeInterval: 5, repeats: false)
        let request = UNNotificationRequest.init(identifier: "FiveSecond", content: content, trigger: trigger)
    
        // Schedule the notification.
        let center = UNUserNotificationCenter.current()
        center.add(request) { (error) in
            print(error)
        }
        print("should have been added")
    }
    
    override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated)
    
        let center = UNUserNotificationCenter.current()
        center.requestAuthorization([.alert, .sound]) { (granted, error) in
        }
    }
    

    And I have a Notification Content Extension in the project as well, but it does not seem to be triggered at all, any ideas what I'm missing? I'm trying the example from the user documentation, but it's not telling me much more or I have missed it.

    Here: https://developer.apple.com/reference/usernotifications/unmutablenotificationcontent

    Also: https://developer.apple.com/reference/usernotificationsui https://developer.apple.com/reference/usernotifications

    Edit:

    So putting the app in the background did the trick.