Swift - 本地通知没有触发

4

我正在使用Swift 3编码,尝试发送立即通知而没有任何延迟或间隔。然而,通知从未被触发。这是我的代码:

ViewController代码

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
}

触发通知函数:

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

我做错了什么?


您可以参考此链接 - https://dev59.com/BloU5IYBdhLWcg3wHEVp - Nilesh
你的通知功能运行良好。为了测试,请将时间间隔增加到5并将应用程序移至后台。(通知横幅将按预期出现。问题在于,当用户通知到达且应用程序处于前台状态时,您没有处理应用程序应该执行的情况) - Muhammad Adnan
2个回答

9
你忽略了在应用程序处于前台时的通知管理,没有指定通知的外观或展示方式。

在添加通知时设置以下行以指定你希望在用户使用应用程序时显示横幅 (iOS 10的新功能)。

在构造UNMutableNotificationContent对象时添加以下代码行:

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

你还应该在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)        
}

@RickGrimesLikesWalkerSoup 使用更新的答案。只需在Appdelegate中添加以下密钥和方法即可。 - Muhammad Adnan
2
setValue(forKey:) 方法是一个完全未记录的键,不能保证在将来(或根本)起作用。它也不是必需的。UNUserNotificationCenter 代理方法是你所需要的一切,并且已经有文档记录。你必须在应用程序委托中特别实现 UNUserNotificationCenterDelegate 并在 didFinishLaunchingWithOptions 中将 UNUserNotificationCenter 的代理设置为应用程序委托,以使其正常工作。 - Bill
11
shouldAlwaysAlertWhileAppIsForeground 在 iOS 12 中不再支持,代码会崩溃。 - Ortwin Gentz
1
@OrtwinGentz 你找到 iOS 12 的替代方案了吗? - the Reverend
3
正如Bill所提到的,实现willPresent委托就足够了。 - Ortwin Gentz
显示剩余3条评论

0

UNUserNotificationCenter.current().requestAuthorization的completion Handler是异步工作的(该方法在不同的线程中处理)。这就是为什么你代码中的“if isGrantedNotificationAccess…”语句在completionHandler完成之前被读取的原因。

有一些解决问题的方法。其中一个方法是使用NotificationCenter通知HomeViewController请求授权方法的结束(请参见下面的示例)。

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
}

仍然没有被触发。 - Jay
我刚刚修复了一个拼写错误的通知-->自我通知,它在我的那一边运作良好。请试一下这个。 - cat
奇怪,我的还没有被触发。你能否也把你的triggerNotification函数发布出来? - Jay

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接