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)
}
}