Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set Cookie with Swift 3

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?

like image 310
Perry Hoekstra Avatar asked Jan 04 '17 18:01

Perry Hoekstra


1 Answers

Swift 3.0

Use the following line to set cookie for urlRequest:

urlRequest?.setValue("somecookie" + cookieString, forHTTPHeaderField: "Cookie")
like image 63
Honey Lakhani Avatar answered Dec 01 '22 00:12

Honey Lakhani