0

我的应用程序和 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() 函数没有被调用?

谢谢你的帮助...

4

1 回答 1

0

添加这一行。

UserDefaults.standard.synchronize()

来自 Apple Docs:由于此方法会定期自动调用,因此只有在无法等待自动同步时才使用此方法

**更新:** 供 IOS 10 使用 UserNotifications framework

(1) 导入 UserNotifications 框架

UNUserNotificationCenterDelegate(2 )添加协议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()


}
于 2017-05-28T11:19:14.113 回答