Set Cookie with Swift 3

6.1k views Asked by At

I am struggling to set a cookie using Swift 3 into a WKWebView. I could not find any example using Swift 3 so using Swift - How to set cookie in NSMutableURLRequest as a starting point, this is what I have:

let url = URL(string: "https://s3-us-west-2.amazonaws.com/foo/helloworld.html")

/* Create cookie and place in cookie storage */
let cookieStorage = HTTPCookieStorage.shared
let cookieHeaderField = ["Set-Cookie": "somecookie=" + cookieString + ";"]
let cookie = HTTPCookie.cookies(withResponseHeaderFields: cookieHeaderField, for: url!)
cookieStorage.setCookies(cookie, for: url, mainDocumentURL: nil)

let urlRequest = URLRequest.init(url: url!)
theWebView.load(urlRequest)

However, when I use the Simulator and inspect it using Safari Develop, it states that I have no cookies set. Thoughts on what I screwed up on or that I failed to take into account?

1

There are 1 answers

0
Honey Lakhani On

Swift 3.0

Use the following line to set cookie for urlRequest:

urlRequest?.setValue("somecookie" + cookieString, forHTTPHeaderField: "Cookie")