如何在iOS中的共享首选项中保存cookie? [英] How to save cookies in shared preferences in iOS?
本文介绍了如何在iOS中的共享首选项中保存cookie?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如何在iOS的共享偏好设置中保存Cookie?
我怎样才能在以后提取它?
我想将 HTTPCookieStorage.shared.cookies 中的cookie保存到用户默认值中然后提取
请在Swift 3中回答
How to save cookies in shared preferences in iOS? And How can I extract it later? I want to save the cookie from HTTPCookieStorage.shared.cookies into user defaults and then extract later Please answer in Swift 3
推荐答案
试用此代码:
商店:
func storeCookies() {
let cookiesStorage = HTTPCookieStorage.shared
let userDefaults = UserDefaults.standard
let serverBaseUrl = "http://example.com"
var cookieDict = [String : AnyObject]()
for cookie in cookiesStorage.cookies(for: NSURL(string: serverBaseUrl)! as URL)! {
cookieDict[cookie.name] = cookie.properties as AnyObject?
}
userDefaults.set(cookieDict, forKey: "cookiesKey")
}
检索:
func restoreCookies() {
let cookiesStorage = HTTPCookieStorage.shared
let userDefaults = UserDefaults.standard
if let cookieDictionary = userDefaults.dictionary(forKey: "cookiesKey") {
for (_, cookieProperties) in cookieDictionary {
if let cookie = HTTPCookie(properties: cookieProperties as! [HTTPCookiePropertyKey : Any] ) {
cookiesStorage.setCookie(cookie)
}
}
}
}
这篇关于如何在iOS中的共享首选项中保存cookie?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文