WKWebView Cookie manipulation

WKWebView Cookie

Under iOS 11, it’s difficult to manage cookies in WKWebView.

WKWebView does not allow to handle cookies.

After iOS 11, APIs opens and we can get/set, remove cookies from WKWebView

This is basic part(codes) of this entry

import UIKit
import WebKit

class ViewController: UIViewController, WKUIDelegate {
    
    @IBOutlet weak var webView: WKWebView!  // interface builder 10.x
    
    var list = [String]()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view.
       
        self.load(urlStr: "https://www.google.com")
        webView.uiDelegate = self
    }
    private func load(urlStr: String) {
        guard let url = URL(string: urlStr) else { return }
        let request = URLRequest(url: url)
        webView.load(request)
    }
}

Get Cookie

Use HTTPCookieStore.

Af for get, API is only getAll, it means that if we want to know specific domain cookie, need to parse from all

nameCookie name
valueCookie value
domainCookie target domain
(can use domain which starts with .(dot)
pathCookie path
portlistThe cookie’s port list
version
Version
expireDateCookie expireDate Date?
isSessionOnlyIndicates session cookie
isHTTPOnlyIndicates cookie should only to be sent to http server
isSecureSecure channel support or not
private func showCookies() {
        // https://developer.apple.com/documentation/webkit/wkhttpcookiestore
        // iOS 11
        let cookieStore = webView.configuration.websiteDataStore.httpCookieStore
        // iOS : 11
        cookieStore.getAllCookies { (cookies) in
            // HTTPCookie : https://developer.apple.com/documentation/foundation/httpcookie
            for cookie in cookies {
                print(cookie.name)
                print(cookie.value)
                print(cookie.domain)
            }
        }
 }

Set Cookie

private func setCookie() {
        var cookieStore = webView.configuration.websiteDataStore.httpCookieStore
        let cookieProperty: [HTTPCookiePropertyKey: Any] =
            [// HTTPCookiePropertyKey.domain: "rakuten.co.jp", // works
             HTTPCookiePropertyKey.domain: ".rakuten.co.jp",   // works
             HTTPCookiePropertyKey.path: "/",
             HTTPCookiePropertyKey.name: "rx",
             HTTPCookiePropertyKey.value: "hello",
             HTTPCookiePropertyKey.secure: "TRUE",
             /*HTTPCookiePropertyKey.expires: Date() */]
        let httpCookie = HTTPCookie(properties: cookieProperty)
        
        cookieStore.setCookie(httpCookie!, completionHandler: {() -> Void in
            // Codes
            print("Cookie Completed")
        })
}

Delete Cookie

Can delete only cookie which matches data to real one.

private func removeCookie() {
        let cookieStore = webView.configuration.websiteDataStore.httpCookieStore
        // Not working
        /*
        let cookieProperty: [HTTPCookiePropertyKey: Any] =
            [HTTPCookiePropertyKey.domain: "youtube.com"]
        let httpCookie = HTTPCookie(properties: cookieProperty)
      */
        // Works
        cookieStore.getAllCookies { (cookies) in
            for cookie in cookies {
                if (cookie.domain == ".youtube.com") {
                    cookieStore.delete(cookie, completionHandler: {() -> Void in
                        print("Delete")
                    })
                }
            }
        }
    }

iOS
スポンサーリンク
Professional Programmer2

コメント