iOS 如何给http链接请求加上cookie

夏风已过 / 2023-08-13 / 原文

先看https是怎么携带cookie的:

var properties: [HTTPCookiePropertyKey: Any] = [:]
properties[.name] = "key"
properties[.path] = "/"
properties[.value] = "value"
properties[.secure] = "true"
properties[.domain] = ".abc.com"

let cookieStore = HTTPCookieStorage.shared
let cookie = HTTPCookie(properties: properties)
if let cookie {
    cookieStore.setCookie(cookie)
}

let config = URLSessionConfiguration.default
let session = URLSession(configuration: config)
let url = URL(string: "https:abc.com")!
var request = URLRequest(url: url)
request.httpMethod = "GET"
let task = session.dataTask(with: request) { (responseData, requestResponse, error) in
}
task.resume()

同样的代码,如果url是 http://abc.com ,那么就会携带不上。

根本原因是: properties[.secure] = "true" ,除非不设置或者设置nil,否则都为true。