好的,当用户在应用程序简介中按下按钮时,它会让他们注册通知。完成此操作后,我尝试保存令牌以发送到我的服务器,并将其显示为空白:
这是我的介绍中的代码。
let settings = UIUserNotificationSettings(forTypes: [.Alert, .Badge, .Sound], categories: nil)
UIApplication.sharedApplication().registerUserNotificationSettings(settings)
var myDelegate = UIApplication.sharedApplication().delegate as! AppDelegate
var tokenString: String = myDelegate.tokenString1
tokenString = tokenString.stringByTrimmingCharactersInSet(NSCharacterSet(charactersInString: "<>"))
tokenString = tokenString.stringByReplacingOccurrencesOfString(" ", withString: "")
NSUserDefaults.standardUserDefaults().setObject(tokenString, forKey: "notification")
NSUserDefaults.standardUserDefaults().synchronize()
这是我的app delegate中的代码:
var tokenString1 = ""
func application(application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: NSData) {
var tokenString: String = deviceToken.description
tokenString = tokenString.stringByTrimmingCharactersInSet(NSCharacterSet(charactersInString: "<>"))
var tokenString1 = tokenString.stringByReplacingOccurrencesOfString(" ", withString: "")
NSUserDefaults.standardUserDefaults().setObject(tokenString1, forKey: "notification")
NSUserDefaults.standardUserDefaults().synchronize()
}
func application(application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: NSError) {
print("Failed to register:", error)
}
答案 0 :(得分:0)
tokenString1
中的本地变量didRegisterForRemoteNotificationsWithDeviceToken
和实例变量tokenString1
是完全不同的对象。首选局部变量,并且永远不会设置实例变量。
解决方案:移除var
didRegister ...
tokenString1 = tokenString.stringByReplacingOccurrencesOfString(" ", withString: "")
根本不需要将令牌保存在用户默认值中。您总是在register方法中获得实际的方法,每次应用程序启动时都会调用该方法。