您必须将通知 accessToken 发送到服务器,它类似于要传递通知的地址。您不必担心 accesstoken 的变化,因为您每次登录时都必须发送它,因此新更新的 accesstoken 也会附加到服务器中。您必须像这样在 Appdelegate 中注册远程通知,然后发送保存的令牌在 nsuserdefault 中登录 API 中的服务器。
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
// Override point for customization after application launch.
let settings = UIUserNotificationSettings(forTypes: [.Alert, .Badge, .Sound], categories: nil)
UIApplication.sharedApplication().registerUserNotificationSettings(settings)
UIApplication.sharedApplication().registerForRemoteNotifications()
return true
}
//Called if successfully registered for APNS.
func application(application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: NSData) {
// let deviceTokenString = NSString(format: "%@", deviceToken) as String
var tokenStr = deviceToken.description
tokenStr = tokenStr.stringByReplacingOccurrencesOfString("<", withString: "", options: [], range: nil)
tokenStr = tokenStr.stringByReplacingOccurrencesOfString(">", withString: "", options: [], range: nil)
tokenStr = tokenStr.stringByReplacingOccurrencesOfString(" ", withString: "", options: [], range: nil)
print(deviceToken.description)
print(tokenStr)
//save the token in NSUserDefaults
NSUserDefaults.standardUserDefaults().setObject(deviceTokenString, forKey: "deviceToken")
}
//Called if unable to register for APNS.
func application(application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: NSError) {
print(error)
}
Reference Apple's Documentation
设备令牌是您向应用发送推送通知的关键
在特定设备上。设备令牌可以更改,因此您的应用需要
每次启动时重新注册并将收到的令牌传回
到你的服务器。如果更新设备令牌失败,远程
通知可能无法到达用户的设备。设备
当用户将备份数据恢复到新的
设备或计算机或重新安装操作系统。迁移时
数据到新设备或计算机,用户必须启动您的应用程序一次
在远程通知可以发送到该设备之前。