【发布时间】:2017-01-12 03:07:11
【问题描述】:
我制作了一个提供推送通知的应用程序。设备令牌更新存在问题。当用户在安装应用程序后立即授予推送通知权限时,设备令牌正在更新。但是如果用户在安装应用后拒绝权限,然后在设置中授予权限,那么设备令牌仍然显示为空。
如果有人能帮助我了解在安装应用程序时最初拒绝权限后用户授予推送通知权限时如何获取设备令牌,我将不胜感激。
这是我实现的代码。
func registerForPushNotification(_ application: UIApplication) {
// set notification types
let types: UIUserNotificationType = [.alert, .badge, .sound]
let notificationSettings = UIUserNotificationSettings(types: types, categories: nil)
application.registerUserNotificationSettings(notificationSettings)
// register
application.registerForRemoteNotifications()
}
// success fetching device token
func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
let tokenChars = (deviceToken as NSData).bytes.bindMemory(to: CChar.self, capacity: deviceToken.count)
var deviceTokenString = ""
for i in 0..<deviceToken.count {
deviceTokenString += String(format: "%02.2hhx", arguments: [tokenChars[i]])
}
print("Device token \(deviceTokenString)")
// register device token
Service.sharedService.registerDeviceToken(deviceTokenString, completion: { (error) -> Void in
if error != nil {
print("Device token not registered: \(error.localizedDescription)")
} else {
print("Device token registered!")
}
})
}
// failed fetching device token
func application(_ application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: Error) {
print("Error registering for remote notifications: \(error.localizedDescription)")
}
【问题讨论】:
标签: ios swift apple-push-notifications