使用uiwebview时如何保存登录会话? 当我通过https网站登录时(在http网站上可以正常使用),我下面的代码无法正常工作:
func saveC() {
let arr = NSMutableArray()
if let cookies = cookieJar.cookies {
for c in cookies {
arr.add(c)
}
let data: Data = NSKeyedArchiver.archivedData(withRootObject: arr)
let ud: UserDefaults = UserDefaults.standard
ud.set(data, forKey: "restoreCookie")
ud.synchronize()
}
}
func loadC() {
let ud: UserDefaults = UserDefaults.standard
let data: Data? = ud.object(forKey: "restoreCookie") as? Data
if let cookie = data {
let datas: NSArray? = NSKeyedUnarchiver.unarchiveObject(with: cookie) as? NSArray
if let cookies = datas {
for c in cookies {
if let cookieObject = c as? HTTPCookie {
HTTPCookieStorage.shared.setCookie(cookieObject)
}
}
}
}
}
在applicationDidEnterBackground和applicationWillTerminate中,使用saveC()保存当前会话。
func applicationDidEnterBackground(_ application: UIApplication) {
Config.shared.saveC()
}
func applicationWillTerminate(_ application: UIApplication) {
Config.shared.saveC()
}
在didFinishLaunchingWithOptions中,我使用loadC()进行还原会话。
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
Config.shared.loadC()
return true
}
但是当我重新启动上述代码的应用程序可以正常工作时,但uiwebview不接受cookie,因此它会强制注销。