Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
A WKWebView subclass that passes cookies after a 302 redirect response.
//
// WKCookieWebView.swift
//
// Created by Jens Reynders on 30/03/2018.
// Copyright (c) 2018 November Five
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
import Foundation
import WebKit
class WKCookieWebView : WKWebView {
private let useRedirectCookieHandling: Bool
init(frame: CGRect, configuration: WKWebViewConfiguration, useRedirectCookieHandling: Bool = false) {
self.useRedirectCookieHandling = useRedirectCookieHandling
super.init(frame: frame, configuration: configuration)
}
required init?(coder: NSCoder) {
self.useRedirectCookieHandling = false
super.init(coder: coder)
}
override func load(_ request: URLRequest) -> WKNavigation? {
guard useRedirectCookieHandling else {
return super.load(request)
}
requestWithCookieHandling(request, success: { (newRequest , response, data) in
DispatchQueue.main.async {
self.syncCookiesInJS()
if let data = data, let response = response {
let _ = self.webViewLoad(data: data, response: response)
} else {
self.syncCookies(newRequest, nil, { (cookieRequest) in
let _ = super.load(cookieRequest)
})
}
}
}, failure: {
// let WKWebView handle the network error
DispatchQueue.main.async {
self.syncCookies(request, nil, { (newRequest) in
let _ = super.load(newRequest)
})
}
})
return nil
}
private func requestWithCookieHandling(_ request: URLRequest, success: @escaping (URLRequest, HTTPURLResponse?, Data?) -> Void, failure: @escaping () -> Void) {
let sessionConfig = URLSessionConfiguration.default
let session = URLSession(configuration: sessionConfig, delegate: self, delegateQueue: nil)
let task = session.dataTask(with: request) { (data, response, error) in
if let _ = error {
failure()
} else {
if let response = response as? HTTPURLResponse {
let code = response.statusCode
if code == 200 {
// for code 200 return data to load data directly
success(request, response, data)
} else if code >= 300 && code < 400 {
// for redirect get location in header,and make a new URLRequest
guard let location = response.allHeaderFields["Location"] as? String, let redirectURL = URL(string: location) else {
failure()
return
}
let request = URLRequest(url: redirectURL, cachePolicy: .reloadIgnoringLocalAndRemoteCacheData, timeoutInterval: 5)
success(request, nil, nil)
} else {
success(request, response, data)
}
}
}
}
task.resume()
}
private func webViewLoad(data: Data, response: URLResponse) -> WKNavigation! {
guard let url = response.url else {
return nil
}
let encode = response.textEncodingName ?? "utf8"
let mine = response.mimeType ?? "text/html"
return self.load(data, mimeType: mine, characterEncodingName: encode, baseURL: url)
}
}
extension WKCookieWebView {
// sync HTTPCookieStorage cookies to URLRequest
private func syncCookies(_ request: URLRequest, _ task: URLSessionTask? = nil, _ completion: @escaping (URLRequest) -> Void) {
var request = request
var cookiesArray = [HTTPCookie]()
if let task = task {
HTTPCookieStorage.shared.getCookiesFor(task, completionHandler: { (cookies) in
if let cookies = cookies {
cookiesArray.append(contentsOf: cookies)
let cookieDict = HTTPCookie.requestHeaderFields(with: cookiesArray)
if let cookieStr = cookieDict["Cookie"] {
request.addValue(cookieStr, forHTTPHeaderField: "Cookie")
}
}
completion(request)
})
} else if let url = request.url {
if let cookies = HTTPCookieStorage.shared.cookies(for: url) {
cookiesArray.append(contentsOf: cookies)
}
let cookieDict = HTTPCookie.requestHeaderFields(with: cookiesArray)
if let cookieStr = cookieDict["Cookie"] {
request.addValue(cookieStr, forHTTPHeaderField: "Cookie")
}
completion(request)
}
}
// MARK: - JS Cookie handling
private func syncCookiesInJS(for request: URLRequest? = nil) {
if let url = request?.url,
let cookies = HTTPCookieStorage.shared.cookies(for: url) {
let script = jsCookiesString(for: cookies)
let cookieScript = WKUserScript(source: script, injectionTime: .atDocumentStart, forMainFrameOnly: false)
self.configuration.userContentController.addUserScript(cookieScript)
} else if let cookies = HTTPCookieStorage.shared.cookies {
let script = jsCookiesString(for: cookies)
let cookieScript = WKUserScript(source: script, injectionTime: .atDocumentStart, forMainFrameOnly: false)
self.configuration.userContentController.addUserScript(cookieScript)
}
}
private func jsCookiesString(for cookies: [HTTPCookie]) -> String {
var result = ""
let dateFormatter = DateFormatter()
dateFormatter.timeZone = TimeZone(abbreviation: "UTC")
dateFormatter.dateFormat = "EEE, d MMM yyyy HH:mm:ss zzz"
for cookie in cookies {
result += "document.cookie='\(cookie.name)=\(cookie.value); domain=\(cookie.domain); path=\(cookie.path); "
if let date = cookie.expiresDate {
result += "expires=\(dateFormatter.string(from: date)); "
}
if (cookie.isSecure) {
result += "secure; "
}
result += "'; "
}
return result
}
}
extension WKCookieWebView : URLSessionTaskDelegate {
func urlSession(_ session: URLSession, task: URLSessionTask, willPerformHTTPRedirection response: HTTPURLResponse, newRequest request: URLRequest, completionHandler: @escaping (URLRequest?) -> Void) {
syncCookies(request) { (newRequest) in
completionHandler(newRequest)
}
}
}
@JenssRey

This comment has been minimized.

Copy link

JenssRey commented Jul 20, 2018

You can read some more information in the blogpost we wrote.
https://novemberfive.co/blog/WKWebView-redirect-with-cookies

@CalvHobbes

This comment has been minimized.

Copy link

CalvHobbes commented Sep 28, 2018

This is fantastic, took me awhile to find this, but it works very well, thank you!

@CalvHobbes

This comment has been minimized.

Copy link

CalvHobbes commented Sep 28, 2018

@JenssRey what the licensing on this?

@nicefella

This comment has been minimized.

Copy link

nicefella commented Oct 24, 2018

Awesome, many thanks!

@JenssRey

This comment has been minimized.

Copy link

JenssRey commented Oct 25, 2018

@CalvHobbes sorry for the late reply, GitHub doesn't seem to notify @-replies here. Glad you like it :)
It is licensed under the general MIT license.

@StackHelp

This comment has been minimized.

Copy link

StackHelp commented Nov 16, 2018

@JenssRey I don't know much about this but when I try to open fb second time, I am not automatically logged in. Is it correct behavior?

@otouronImpak

This comment has been minimized.

Copy link

otouronImpak commented Dec 17, 2018

need a pod man ;-)

@DimitryDushkin

This comment has been minimized.

Copy link

DimitryDushkin commented Jan 15, 2019

Is there WKWebView bug report for this? I can make one if it is not present yet.

@AlissonManfron

This comment has been minimized.

Copy link

AlissonManfron commented Jan 29, 2019

Thanks!!

@aecvargas

This comment has been minimized.

Copy link

aecvargas commented Feb 7, 2019

@JenssRey I am working with Ionic1/AngularJS and not Swift files. I have set up an Android and iOS platform via ionic/cordova commands to my application and I don't quite understand how I can apply this fix to my issue.

@flexaddicted

This comment has been minimized.

Copy link

flexaddicted commented Mar 11, 2019

Hi @JenssRey! Thanks for sharing. This was my previous solution https://medium.com/@flexaddicted/how-to-set-wkwebview-cookie-accept-policy-d8a2d3b77420 but from iOS 12 it seems not working anymore. Can you tell me if your solution resolves it? Thanks, Lorenzo

@noorulain17

This comment has been minimized.

Copy link

noorulain17 commented Jul 9, 2019

It works very well on iOS 10. Thanks a lot 👍

@f-gonzalez

This comment has been minimized.

Copy link

f-gonzalez commented Aug 1, 2019

Thanks a lot!

@ShanbhagVinit

This comment has been minimized.

Copy link

ShanbhagVinit commented Dec 31, 2019

Thanks for the solution. There is some thing that i found with this. When url consists of the query parameters and the redirected url gets loaded, the subsequent requests should have the query params, whereas they get lost in the process.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.