2015-03-30 83 views
1

現在我正在通過didRegisterForRemoteNotificationsWithDeviceToken獲取設備令牌。但是,在用戶登錄後,我需要在應用程序中稍後使用設備令牌。我可以在哪裏存儲iOS設備令牌供以後使用?

如何從稍後的其他應用程序訪問deviceToken,如果不能,我如何/在哪裏可以將它存儲在didRegisterForRemoteNotificationsWithDeviceToken所以我可以稍後檢索它?

回答

2

最簡單的方法是使用NSUserDefaults

保存:

NSUserDefaults * ud = [NSUserDefaults standardUserDefaults]; 
[ud setObject:myPushToken forKey:@"currentPushToken"]; 
[ud synchronize]; 

恢復:

NSString * currentPushToken = [[NSUserDefaults standardUserDefaults] objectForKey:@"currentPushToken"]; 
2

其更好地使用keychain這樣的數據。

添加此類funcs中到項目

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()) 
相關問題