iPhone: NSHTTPCookie is not saved across app restarts

后端 未结 7 549
梦如初夏
梦如初夏 2020-12-01 05:14

In my iPhone app, I want to be able to reuse the same server-side session when my app restarts. A session on the server is identified by a cookie, which is sent on each requ

7条回答
  •  醉梦人生
    2020-12-01 05:46

    Session-only cookies will expire by their nature. You can store them manually in Keychain if you really want it. I prefer Keychain to saving in UserDefaults or archiving because cookies are better be secured, just like user's password.

    Unfortunately saving session-only cookies is not very helpful, the code below is just an illustration how to store cookies, but can't 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)
                }
            }
        }
    }
    

提交回复
热议问题