는 세션 전용 쿠키가 자연 만료됩니다. 키 체인을 원할 경우 수동으로 키 체인에 저장할 수 있습니다.나는 UserDefaults에 저장하거나 보관하는 것이 키 체인보다 사용자의 암호처럼 쿠키가 더 안전하기 때문에 선호합니다.
불행히도 세션 전용 쿠키를 저장하는 것은별로 도움이되지 않습니다. 아래의 코드는 쿠키를 저장하는 방법을 보여 주지만 서버를 제어 할 수있는 경우를 제외하고 서버가 쿠키를 허용하지 않습니다.
스위프트 2.2
// Saving into Keychain
if let cookies = NSHTTPCookieStorage.sharedHTTPCookieStorage().cookies {
let cookiesData: NSData = NSKeyedArchiver.archivedDataWithRootObject(cookies)
let userAccount = "some unique string to identify the item in Keychain, in my case I use username"
let domain = "some other string you can use in combination with userAccount to identify the item"
let keychainQuery: [NSString: NSObject] = [
kSecClass: kSecClassGenericPassword,
kSecAttrAccount: userAccount + "cookies",
kSecAttrService: domain,
kSecValueData: cookiesData]
SecItemDelete(keychainQuery as CFDictionaryRef) //Trying to delete the item from Keychaing just in case it already exists there
let status: OSStatus = SecItemAdd(keychainQuery as CFDictionaryRef, nil)
if (status == errSecSuccess) {
print("Cookies succesfully saved into Keychain")
}
}
// Getting from Keychain
let userAccount = "some unique string to identify the item in Keychain, in my case I use username"
let domain = "some other string you can use in combination with userAccount to identify the item"
let keychainQueryForCookies: [NSString: NSObject] = [
kSecClass: kSecClassGenericPassword,
kSecAttrService: domain, // we use JIRA URL as service string for Keychain
kSecAttrAccount: userAccount + "cookies",
kSecReturnData: kCFBooleanTrue,
kSecMatchLimit: kSecMatchLimitOne]
var rawResultForCookies: AnyObject?
let status: OSStatus = SecItemCopyMatching(keychainQueryForCookies, &rawResultForCookies)
if (status == errSecSuccess) {
let retrievedData = rawResultForCookies as? NSData
if let unwrappedData = retrievedData {
if let cookies = NSKeyedUnarchiver.unarchiveObjectWithData(unwrappedData) as? [NSHTTPCookie] {
for aCookie in cookies {
NSHTTPCookieStorage.sharedHTTPCookieStorage().setCookie(aCookie)
}
}
}
}
nsuserdefaults를 동기화해야합니까? – ninjaneer
바로 저장해야하는 경우 동기화가 필요합니다. 그렇지 않으면 그들은 나중에 어떤 중간 시대에 구원받을 것입니다. 다음은 doc 페이지입니다. http://developer.apple.com/library/mac/#documentation/Cocoa/Reference/Foundation/Classes/NSUserDefaults_Class/Reference/Reference.html#//apple_ref/occ/instm/NSUserDefaults/synchronize –