8

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?

Community
  • 1
  • 1
Perry Hoekstra
  • 2,687
  • 3
  • 33
  • 52

1 Answers1

1

Swift 3.0

Use the following line to set cookie for urlRequest:

urlRequest?.setValue("somecookie" + cookieString, forHTTPHeaderField: "Cookie")
Honey Lakhani
  • 83
  • 1
  • 7