现在我通过didRegisterForRemoteNotificationsWithDeviceToken
获取设备令牌。但是,我需要在用户登录后在我的应用程序中使用设备令牌。
如何在以后从应用程序的其他位置访问deviceToken,如果我不能,我将如何/在哪里将其存储在didRegisterForRemoteNotificationsWithDeviceToken
中,以便稍后可以检索它?
答案 0 :(得分:3)
最好将keychain
用于此类数据。
将此类功能添加到您的项目
import UIKit
import Security
class Keychain {
class func save(key: String, data: NSData) -> Bool {
let query = [
kSecClass as String : kSecClassGenericPassword as String,
kSecAttrAccount as String : key,
kSecValueData as String : data ]
SecItemDelete(query as CFDictionaryRef)
let status: OSStatus = SecItemAdd(query as CFDictionaryRef, nil)
return status == noErr
}
class func load(key: String) -> NSData? {
let query = [
kSecClass as String : kSecClassGenericPassword,
kSecAttrAccount as String : key,
kSecReturnData as String : kCFBooleanTrue,
kSecMatchLimit as String : kSecMatchLimitOne ]
var dataTypeRef :Unmanaged<AnyObject>?
let status: OSStatus = SecItemCopyMatching(query, &dataTypeRef)
if status == noErr {
return (dataTypeRef!.takeRetainedValue() as NSData)
} else {
return nil
}
}
class func delete(key: String) -> Bool {
let query = [
kSecClass as String : kSecClassGenericPassword,
kSecAttrAccount as String : key ]
let status: OSStatus = SecItemDelete(query as CFDictionaryRef)
return status == noErr
}
class func clear() -> Bool {
let query = [ kSecClass as String : kSecClassGenericPassword ]
let status: OSStatus = SecItemDelete(query as CFDictionaryRef)
return status == noErr
}
}
你就像这样使用它
要存储(传递是您的案例中的字符串,令牌)
if let data = pass.dataUsingEncoding(NSUTF8StringEncoding,allowLossyConversion: false) {
let saveSuccess = Keychain.save("Password", data: data)
}
加载
data = Keychain.load("Password")
var pass =NSString(data: data, encoding: UInt())
答案 1 :(得分:2)
最简单的方法是使用NSUserDefaults
保存:
NSUserDefaults * ud = [NSUserDefaults standardUserDefaults];
[ud setObject:myPushToken forKey:@"currentPushToken"];
[ud synchronize];
恢复:
NSString * currentPushToken = [[NSUserDefaults standardUserDefaults] objectForKey:@"currentPushToken"];