didReceiveRemoteNotification没有调用 - 为什么?

时间:2017-05-28 09:13:53

标签: ios swift notifications nsusernotification

我的应用和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秒后,我收到了通知。到那时,一切都很好。问题是:当它收到提醒时,应该在app委托中调用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() - 函数不被调用?

感谢您的帮助......

1 个答案:

答案 0 :(得分:0)

添加此行。

UserDefaults.standard.synchronize()

From Apple Docs:因为此方法是定期自动调用的,所以只有在您无法等待自动同步时才使用此方法

**更新:** 对于IOS 10,请使用UserNotifications framework

(1)导入UserNotifications框架

(2)在UNUserNotificationCenterDelegate

中添加协议AppDelegate.swift

(3)在didFinishLaunchingWithOptions启用/禁用功能

let notificationCenter = UNUserNotificationCenter.current()
notificationCenter.requestAuthorization(options:[.badge, .alert, .sound]) { (granted, error) in

}
application.registerForRemoteNotifications()

(4)对于设备令牌

func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {

    let deviceTokenAsString = deviceToken.reduce("", {$0 + String(format: "%02X", $1)})
    print(deviceTokenAsString)


}

(5)如果错误

func application(_ application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: Error) {

        print(error)
}

如果收到通知,应该调用delgate:

func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable : Any], fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) {

    completionHandler(UIBackgroundFetchResult.noData)

UserDefaults.standard.set(true, forKey: "didReceiveRemoteNotification")
UserDefaults.standard.synchronize()


}