Session-only cookies expire in nature. You can save them manually in Keychain if you really want to. I prefer Keychain to be stored in UserDefaults or archived because cookies are better protected, as is the user's password.
Unfortunately, saving cookies only for the session is not very useful, the code below is just an illustration of how to store cookies, but cannot force the server to accept such cookies in any way (unless you can control the server).
Swift 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) } } } }
Vitalii Jul 23 '16 at 17:21 2016-07-23 17:21
source share