iPhone: NSHTTPCookie is not saved across app restarts

后端 未结 7 547
梦如初夏
梦如初夏 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 06:05

    I have upvoted @TomIrving's answer and am elaborating here because many users will not see the very important comment in which he says:

    "You need to set an expiration date, otherwise the cookie is assumed to be session only."

    Basically, the cookie will be deleted when you close your app UNLESS the cookie has an expiration date in the future.

    You don't need to store and restore the cookies in and from NSUserDefaults if you have control over the server and can ask it to set the "Expires" header to something in the future. If you don't have control over the server or do not wish to override your server's behavior, you can 'trick' your app by changing the expiresDate from within it:

    • Get the cookie you want to modify from [[NSHTTPCookieStorage sharedHTTPCookieStorage] cookies]
    • Copy its properties to a new NSMutableDictionary , changing the "Expires" value to a date in the future.
    • Create a new cookie from the new NSMutableDictionary using: [NSHTTPCookie.cookieWithProperties:]
    • Save the newly created cookie using [[NSHTTPCookieStorage sharedHTTPCookieStorage] setCookie newCookie]

    When you reopen your app, you'll notice that the cookie has not been deleted.

    0 讨论(0)
提交回复
热议问题