Add Local Notification in iOS 10 - Swift 3
Asked Answered
C

5

30

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.

Coracle answered 14/6, 2016 at 8:55 Comment(2)
You can refer this link for detailed usage jayprakashdubey.blogspot.in/2016/07/…Anticholinergic
how to set different date components or how to call local notfications multiple times?Jasik
W
30

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.

Wace answered 14/6, 2016 at 9:24 Comment(5)
Yes I have this, still no luck. Do you have a full app example so I can see if I missed anything?Coracle
@Coracle in ios10..we can display notification while the app is in foreground as of android...see the sample project....Selenite
hi @anish I downloaded the app and ran on simulator. I don't see a notification?Heartwood
Ahh..demo project was in Xcode 8 beta...I have updated example for the Xcode 8...Selenite
how to set different date components or how to call local notfications multiple times?Jasik
S
17

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 .

Surfacetoair answered 15/6, 2016 at 9:6 Comment(7)
Hi , I ran you demo but it gives me exception Assertion failure in -[UNTimeIntervalNotificationTrigger _initWithTimeInterval:repeats:] while executing UNTimeIntervalNotificationTrigger *trigger = [UNTimeIntervalNotificationTrigger triggerWithTimeInterval:5.f repeats:YES];.Oeo
Why are you writing in Objective-C?Diffractometer
Because he can ;)Cali
Local notifications are not firing....Pl check my postMeanly
@EktaPadaliya Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'time interval must be at least 60 if repeating'Surfacetoair
@ElonChan Hi Elon, I have added the local notification you mentioned here for iOS 10. I have also checked that from iOS 10 we can show notification in foreground as well but I am not able to successfully implement that. could you please help me with that ?Stanhope
HI, i tried u r demo. but it is not showing any notifications.Sophia
K
1

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.

Kwang answered 24/12, 2016 at 10:21 Comment(3)
Don't see the point of a huge framework to do something that simple.Coracle
Apple's or Firebase's?Eldon
This should really be used without a framework. It's very simple to doKowalczyk
D
1

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])
    }
    
Deejay answered 5/7, 2018 at 14:57 Comment(2)
Cannot assign value of type 'MainScreen' to type 'UNUserNotificationCenterDelegate?', when using in view did load, UNUserNotificationCenter.current().delegate = selfFite
You might want to add UNUserNotificationCenterDelegate to your screen (ViewController)Deejay
P
0

I have made an implementation for Swift 3 which may help, you can check it here: https://mcmap.net/q/169615/-local-and-push-notifications-in-ios-version-compatible

Pray answered 30/7, 2017 at 16:52 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.