我正在尝试在我的HTTP请求中设置cookie,我认为下面的代码可以工作:
let request = NSMutableURLRequest(URL: url) request.HTTPMethod = "GET" request.setValue("key=value;", forHTTPHeaderField: "Cookie")
但是这段代码不起作用.有没有人知道如何设置它?
更新了Swift 3的答案
你想看看HTTPCookieStorage.
// First let jar = HTTPCookieStorage.shared let cookieHeaderField = ["Set-Cookie": "key=value"] // Or ["Set-Cookie": "key=value, key2=value2"] for multiple cookies let cookies = HTTPCookie.cookies(withResponseHeaderFields: cookieHeaderField, for: url) jar.setCookies(cookies, for: url, mainDocumentURL: url) // Then var request = URLRequest(url: url)
swift的原始答案2
你想看看NSHTTPCookieStorage.
// First let jar = NSHTTPCookieStorage.sharedHTTPCookieStorage() let cookieHeaderField = ["Set-Cookie": "key=value"] // Or ["Set-Cookie": "key=value, key2=value2"] for multiple cookies let cookies = NSHTTPCookie.cookiesWithResponseHeaderFields(cookieHeaderField, forURL: url) jar.setCookies(cookies, forURL: url, mainDocumentURL: url) // Then let request = NSMutableURLRequest(URL: url)