我的应用程序和 UserNotifications 框架有问题。我有一个带有 sendNotification() 函数的主视图控制器,如下所示:
let content = UNMutableNotificationContent()
content.title = "Water Reminder"
content.body = "What about a glass of water?"
content.sound = UNNotificationSound.default()
let testTrigger = UNTimeIntervalNotificationTrigger(timeInterval: 30, repeats: false)
let identifier = Int(arc4random_uniform(999999999))
let request = UNNotificationRequest(identifier: "\(identifier)", content: content, trigger: testTrigger)
center.add(request, withCompletionHandler: {
(error) in
if let error = error {
print("Didn't add notification request. \(error)")
}
})
触发器仅用于测试。好吧,30 秒后,我收到了通知。到那时,一切都很好。问题是:当它收到提醒时,它应该调用应用程序委托中的 didReceiveRemoteNotification() 函数,但它没有。这是我的功能:
func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable : Any], fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) {
UserDefaults.standard.set(true, forKey: "didReceiveRemoteNotification")
}
所以,我收到了通知,在 didFinishLaunchingWithOptions() 函数中插入了这行代码:
print("\(UserDefaults.standard.bool(forKey: "didReceiveRemoteNotification")")
即使我收到了通知,它也给了我错误的信息。这怎么可能?
在功能部分,通知和后台获取的后台模式以及推送通知被激活。应用程序委托和视图控制器都导入了 UserNotifications,添加为 UNUserNotificationCenterDelegate 并且都有一个 center.delegate = self 代码之一。为什么它不起作用?为什么我的 didReceiveRemoteNotification() 函数没有被调用?
谢谢你的帮助...