I have this simple application with a UIWebView, but I can not use the cookies to store the loggin or keep the user logged.
I open the application, I log in, I close the application, and when I open it again the login fields are blank. I would like at least that the user and password were filled based on cookies
this is the code from viewController.swift
import UIKit
class ViewController: UIViewController {
@IBOutlet var myWebView: UIWebView!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
let url = URL(string: "https://dashboardgrouping.correadasilva.com")
myWebView.loadRequest(URLRequest(url:url!))
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?)->Bool {
loadHTTPCookies()
return true
}
func applicationDidEnterBackground(_ application: UIApplication) {
saveCookies()
}
func applicationWillEnterForeground(_ application: UIApplication) {
loadHTTPCookies()
}
func applicationWillTerminate(_ application: UIApplication) {
saveCookies()
}
func loadHTTPCookies() {
if let cookieDict = UserDefaults.standard.value(forKey: "cookieArray") as?NSMutableArray {
for c in cookieDict {
let cookies = UserDefaults.standard.value(forKey: c as!String) as!NSDictionary
let cookie = HTTPCookie(properties: cookies as![HTTPCookiePropertyKey: Any])
HTTPCookieStorage.shared.setCookie(cookie!)
}
}
}
func saveCookies() {
let cookieArray = NSMutableArray()
if let savedC = HTTPCookieStorage.shared.cookies {
for c: HTTPCookie in savedC {
let cookieProps = NSMutableDictionary()
cookieArray.add(c.name)
cookieProps.setValue(c.name, forKey: HTTPCookiePropertyKey.name.rawValue)
cookieProps.setValue(c.value, forKey: HTTPCookiePropertyKey.value.rawValue)
cookieProps.setValue(c.domain, forKey: HTTPCookiePropertyKey.domain.rawValue)
cookieProps.setValue(c.path, forKey: HTTPCookiePropertyKey.path.rawValue)
cookieProps.setValue(c.version, forKey: HTTPCookiePropertyKey.version.rawValue)
cookieProps.setValue(NSDate().addingTimeInterval(2629743), forKey: HTTPCookiePropertyKey.expires.rawValue)
UserDefaults.standard.setValue(cookieProps, forKey: c.name)
UserDefaults.standard.synchronize()
}
}
UserDefaults.standard.setValue(cookieArray, forKey: "cookieArray")
}
}