Kex*_*Kex 20 apple-push-notifications ios swift swift3
尝试为iOS10设置推送通知.以前它是否适用于10以下的版本.
阅读一些指南我的设置是这样的:
// Register for the defined notifications
        if #available(iOS 10.0, *) {
            let center = UNUserNotificationCenter.current()
            center.delegate = UIApplication.shared.delegate as! AppDelegate
            center.requestAuthorization(options: [.alert, .badge, .sound]) { (granted, error) in
                if error == nil {
                    UIApplication.shared.registerForRemoteNotifications()
                }
            }
        } else {
            // Fallback on earlier versions
            let notificationSettings = UIUserNotificationSettings(types: [.alert, .badge, .sound], categories: [autoCancelCategory])
            UIApplication.shared.registerUserNotificationSettings(notificationSettings)
            UIApplication.shared.registerForRemoteNotifications()
        }
这是在我的一个视图控制器中登录^时调用的.
现在AppDelegate,它符合UNUserNotificationCenterDelegate,我有这些方法:
@available(iOS 10.0, *)
func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
    print("Got a push!")
}
@available(iOS 10.0, *)
func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) {
    print("Got a push!")
}
我也有:
 func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
    let settings = UserDefaults.standard
    settings.setValue(deviceToken, forKey: "deviceToken")
}
设备令牌作为上传到服务器Data,这对以前的版本工作正常.
我检查过服务器上的令牌与手机上的令牌匹配.
我已经为所有目标启用了推送通知Capabilities,我也已经勾选了Add the push Notifications entitlement to your entitlements file.
在推动时根本没有收到任何东西.
我在这里做错了什么想法?任何指针都会非常感激!
谢谢!
编辑:我也注意到推送通知在iOS9中不起作用.
回答这个问题,也许对其他人有用。我的令牌错了。编码随着最近的更新而改变。我实际上确实在整个堆栈溢出中搜索了这个,据我了解,我必须Data使用String. base64string但是我注意到这个字符串中有一些奇怪的字符,例如\. 我最终做出了Data扩展:
extension Data {
    func hexString() -> String {
        return self.reduce("") { string, byte in
            string + String(format: "%02X", byte)
        }
    }
}
这会将其转换Data为正确的格式。因此,如果这就是您进行转换的方式,并且设置了所有权利,请记住添加新方法:
@available(iOS 10.0, *)
func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
    print("Got a push!")
}
@available(iOS 10.0, *)
func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) {
    print("Got a push!")
}
并在一切中设置委托对象didFinishLaunchingWithOptions应该很顺利。
| 归档时间: | 
 | 
| 查看次数: | 1010 次 | 
| 最近记录: |