LoginSignup
5

More than 5 years have passed since last update.

Swift3 で Cookie を自力で作成したい場合

Posted at

ロジックテスト書いてて、自力で Cookie を作成する必要があったのでメモ。
Cookie の各種パラメータを設定し HTTPCookie を作成します。

class CookieHelper {
    func generate(key: String = "key", value: String = "value") -> HTTPCookie {
        let cookieProperty: [HTTPCookiePropertyKey: Any] = [
            HTTPCookiePropertyKey.domain: "example.com",
            HTTPCookiePropertyKey.path: "/",
            HTTPCookiePropertyKey.name: key,
            HTTPCookiePropertyKey.value: value,
            HTTPCookiePropertyKey.secure: "TRUE",
            HTTPCookiePropertyKey.expires: Date()
        ]

        return HTTPCookie(properties: cookieProperty)!
    }
}

こんな感じで利用できます。

CookieHelper().generate()
CookieHelper().generate(key: "key", value: "value")

参考

ios - How To Set a Cookie for a UIWebView manually in Swift - Stack Overflow

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
5