Skip to content

Instantly share code, notes, and snippets.

@novemberfiveco-gists
Last active June 26, 2023 10:02
Show Gist options
  • Star 58 You must be signed in to star a gist
  • Fork 15 You must be signed in to fork a gist
  • Save novemberfiveco-gists/798e3cbb80b0d1a9f75d6ddfd0f87071 to your computer and use it in GitHub Desktop.
Save novemberfiveco-gists/798e3cbb80b0d1a9f75d6ddfd0f87071 to your computer and use it in GitHub Desktop.
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
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
Copy link

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

@CalvHobbes
Copy link

@JenssRey what the licensing on this?

@nicefella
Copy link

Awesome, many thanks!

@JenssRey
Copy link

@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
Copy link

@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
Copy link

need a pod man ;-)

@DimitryDushkin
Copy link

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

@AlissonManfron
Copy link

Thanks!!

@allanevargas
Copy link

allanevargas 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
Copy link

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
Copy link

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

@f-gonzalez
Copy link

Thanks a lot!

@ShanbhagVinit
Copy link

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.

@bbtyou
Copy link

bbtyou commented Dec 1, 2020

can not support goback.

@evertonco
Copy link

evertonco commented Dec 9, 2020

Hi, where I put this file?

@vichhai
Copy link

vichhai commented Jun 29, 2021

Thank you for the solution. But it doesn't support goBack().

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment