I'm building an app that uses Single Sign On for users to log in. After the user enters a successful ID and password, the web side of things returns headers which I grab and store in my app. The WKWebView also sets a cookie that the user successfully logged in. This is what I want to avoid or undo.
The undesired behavior that I'm seeing is that if I log in a user, everything goes well, and then I log them out and go to log back in again, the WKWebView thinks the user is still logged in and takes them to an undesired URL.
In iOS 9, mitigating this is fairly simple:
let config = WKWebViewConfiguration()
config.websiteDataStore = WKWebsiteDataStore.nonPersistentDataStore()
let webView = WKWebView(frame: .zero, configuration: config)
However in iOS 8.4, making making sure the cookies are clear each time the user goes in to load the Single Sign On URL is more complicated.
I've tried approaches where I loop through cookies in NSHTTPCookieStorage.sharedHTTPCookieStorage()
and remove them. Unfortunately, the cookie count is 0.
I've also tried removing the /Cookies
directory in NSFileManager.defaultManager()
. This also does not work.
One thing that kind of worked was doing the following. Although this approach didn't allow me to get the headers because a redirect after login needed to happen and this interfered (in iOS 9+ and 8.4)
req = NSMutableURLRequest(URL: url)
req?.HTTPShouldHandleCookies = false
let webView = WKWebView()
webView.loadRequest(req ?? NSURLRequest(URL: url))
I'd prefer to clear cookies in the deinit
of my view that holds my WKWebView if that's a possible solution here.