Swift - Local Notification doesn't get triggered

ぐ巨炮叔叔 提交于 2019-12-08 02:45:09

问题


I am coding in Swift 3 and I am simply trying to send a notification now without any delays or intervals. However the notification never gets triggered. Here's my code..

The ViewController code

import UserNotifications

class HomeViewController: UIViewController{
    var isGrantedNotificationAccess:Bool = false

    override func viewDidLoad() {
        super.viewDidLoad()

        UNUserNotificationCenter.current().requestAuthorization(
            options: [.alert,.sound,.badge],
            completionHandler: { (granted,error) in
                self.isGrantedNotificationAccess = granted
        })

        if isGrantedNotificationAccess{
            triggerNotification()
        }
    }

    //triggerNotification func goes here
}

triggerNotification function:

func triggerNotification(){
    let content = UNMutableNotificationContent()
    content.title = NSString.localizedUserNotificationString(forKey: "Notification Testing", arguments: nil)
    content.body = NSString.localizedUserNotificationString(forKey: "This is a test", arguments: nil)
    content.sound = UNNotificationSound.default()
    content.badge = (UIApplication.shared.applicationIconBadgeNumber + 1) as NSNumber;
    let trigger = UNTimeIntervalNotificationTrigger(
        timeInterval: 1.0,
        repeats: false)

    let request = UNNotificationRequest.init(identifier: "testTriggerNotif", content: content, trigger: trigger)

    let center = UNUserNotificationCenter.current()
    center.add(request)
}

What am I doing wrong?


回答1:


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)        
}



回答2:


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
}


来源:https://stackoverflow.com/questions/41373321/swift-local-notification-doesnt-get-triggered

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!