Swift - Local Notification doesn't get triggered

北城以北 提交于 2019-12-06 10:37:56
Muhammad Adnan

You were missing the handling, when the app is in foreground, you were not specifying how the notifications would look like or be presented.

Set below line while adding notification to specify that you want to show banner while user is using app (iOS 10 new feature).

Add the following line of code when constructing your UNMutableNotificationContent object:

content.setValue("YES", forKeyPath: "shouldAlwaysAlertWhileAppIsForeground")

You should also add the following method in your AppDelegate:

// This method will be called when app received push notifications in foreground

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

UNUserNotificationCenter.current().requestAuthorization's completion Handler works asynchronously (the method is handled in different thread). That's why "if isGrantedNotificationAccess.." statement in your code was read before completionHandler was completed.

There are some ways to resolve the issue. One is to use NotificationCenter to notify the end of the requestAuthorization method to HomeViewController (see the example below).

import UserNotifications

class HomeViewController: UIViewController{

let notification = Notification.Name("requestAuthorizationComplete")

override func viewDidLoad() {
    super.viewDidLoad()

    // Register self as Observer to receive notification
    NotificationCenter.default.addObserver(self, selector: #selector(self.triggerNotification), name: notification, object: nil)

    UNUserNotificationCenter.current().requestAuthorization(
        options: [.alert,.sound,.badge],
        completionHandler: { (granted,error) in
        NotificationCenter.default.post(name: self.notification, object: nil)
    })

}

func triggerNotification(notification:NSNotification?){
 // this function will be called once requestAuthorization is complete
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!