【发布时间】:2017-05-28 09:13:52
【问题描述】:
我的应用和 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() 函数没有被调用?
感谢您的帮助...
【问题讨论】:
标签: ios swift notifications nsusernotification