11
13

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

[iOS][Swift] WKWebViewにcookieをセットする

Last updated at Posted at 2019-03-12

WKWebViewにcookieをセットする方法

cookieにセットするキーと値をDictionaryに入れておく

var cookies = Dictionary<String, String>()

参考

            var request = URLRequest(url: URL(string: "https://example.com/")!)

            // Cookieを追加する
            var hTTPCookies = [HTTPCookie]()
            for (key, value) in cookies {
                hTTPCookies.append(MyClass.makeCookie(key: key, value: value))
            }

            let headers = HTTPCookie.requestHeaderFields(with: hTTPCookies)
            for (name, value) in headers {
                request.addValue(value, forHTTPHeaderField: name)
            }
            webView.load(request)

DictionaryからCookieを作成するクラスメソッド

MyClass
    class func makeCookie(key:String, value:String) -> HTTPCookie{
        let cookies = HTTPCookie(properties: [
            .domain: "example.com",
            .path: "/",
            .name: key,
            .value: value,
            .secure: "FALSE",
            .expires: NSDate(timeIntervalSinceNow: 31556926)
            ])!
        return cookies
    }
11
13
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
11
13

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?