使用NSUserdefault将设计令牌检索为字符串

时间:2017-05-24 19:21:24

标签: xcode swift3 push-notification

func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
    // Convert token to string


    let deviceTokenString = deviceToken.reduce("", {$0 + String(format: "%02X", $1)})

    // Print it to console
    print("APNs device token: \(deviceTokenString)")
    UserDataSingleton.sharedDataContainer.token = deviceTokenString

然后我在视图控制器中的viewdidloaud中打印UserDataSingleton.sharedDataContainer.token

override func viewDidLoad() {
    super.viewDidLoad()

    print(UserDataSingleton.sharedDataContainer.token)

它打印为零!

如何将令牌保存为字符串以将其发送到我的后端?

 struct DefaultsKey
 {

static let Token = "token"


}


class UserDataSingleton
   {
      static let sharedDataContainer = UserDataSingleton()
init() {
    let defaults = UserDefaults.standard

    self.token = defaults.object(forKey:DefaultsKey.Token) as? String

}
var token : String?{
    didSet {
        let defaults = UserDefaults.standard
        defaults.set(token, forKey:DefaultsKey.Token)

    }
}

0 个答案:

没有答案