Swift 4.2
Please add this extension to your controller
extension UserDefaults {
/// A dictionary of properties representing a cookie.
typealias CookieProperties = [HTTPCookiePropertyKey: Any]
/// The `UserDefaults` key for accessing cookies.
private static let cookieKey = "cookies"
/// Saves all cookies currently in the shared `HTTPCookieStorage` to the shared `UserDefaults`.
func saveCookies() {
guard let cookies = HTTPCookieStorage.shared.cookies else {
return
}
let cookiePropertiesArray = cookies.compactMap { $0.properties }
set(cookiePropertiesArray, forKey: UserDefaults.cookieKey)
synchronize()
}
/// Loads all cookies stored in the shared `UserDefaults` and adds them to the current shared `HTTPCookieStorage`.
func loadCoookies() {
let cookiePropertiesArray = value(forKey: UserDefaults.cookieKey) as? [CookieProperties]
cookiePropertiesArray?.forEach {
if let cookie = HTTPCookie(properties: $0) {
HTTPCookieStorage.shared.setCookie(cookie)
}
}
}
}
And replace in AppDelegate this code lines:
func applicationDidEnterBackground(_ application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(_ application: UIApplication) {
// Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(_ application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(_ application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}
with this code lines:
func applicationDidBecomeActive(_ application: UIApplication) {
UserDefaults.standard.loadCoookies()
}
func applicationWillEnterForeground(_ application: UIApplication) {
UserDefaults.standard.loadCoookies()
}
func applicationDidEnterBackground(_ application: UIApplication) {
UserDefaults.standard.saveCookies()
}
func applicationWillTerminate(_ application: UIApplication) {
UserDefaults.standard.saveCookies()
}