Right now I'm getting the device token via didRegisterForRemoteNotificationsWithDeviceToken
. However, I need to use the device token later on in my application after my user logs in.
How can I access the deviceToken from elsewhere in application later on, and if I cannot, how/where can I store it in didRegisterForRemoteNotificationsWithDeviceToken
so I can retrieve it later on?
The most simple way is to use NSUserDefaults
Saving:
NSUserDefaults * ud = [NSUserDefaults standardUserDefaults];
[ud setObject:myPushToken forKey:@"currentPushToken"];
[ud synchronize];
Restoring:
NSString * currentPushToken = [[NSUserDefaults standardUserDefaults] objectForKey:@"currentPushToken"];
Its better to use keychain
for such data.
Add this class funcs to your project
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
}
}
And you use it like this
To store (pass is the string in your case , the token)
if let data = pass.dataUsingEncoding(NSUTF8StringEncoding,allowLossyConversion: false) {
let saveSuccess = Keychain.save("Password", data: data)
}
To load
data = Keychain.load("Password")
var pass =NSString(data: data, encoding: UInt())