Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add Local Notification in iOS 10 - Swift 3

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.

like image 799
Bjarte Avatar asked Jun 14 '16 08:06

Bjarte


People also ask

How does Swift handle local notifications?

Create and Register a Notification Request // Create the request let uuidString = UUID(). uuidString let request = UNNotificationRequest(identifier: uuidString, content: content, trigger: trigger) // Schedule the request with the system. let notificationCenter = UNUserNotificationCenter. current() notificationCenter.

What is difference between push notification and local notification?

The essential difference between local notifications and push notifications is simple: Local notifications are scheduled by an app locally and are delivered by the same device. Push notifications are sent by a remote server (its provider) which sends these notifications to devices on which the app is installed.

Can you send local notifications while app is in background?

Notifications could be created at any moment (on Foreground, Background or even when the application is terminated/killed).


4 Answers

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.

like image 195
Anish Parajuli 웃 Avatar answered Nov 01 '22 03:11

Anish Parajuli 웃


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 .

like image 17
ChenYilong Avatar answered Nov 01 '22 04:11

ChenYilong


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.

like image 1
ibrahimyilmaz Avatar answered Nov 01 '22 03:11

ibrahimyilmaz


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])
    }
    
like image 1
Allen Avatar answered Nov 01 '22 03:11

Allen