func getCookiesAndAuthToken(_ url: URL?) {
guard let url else { return }
var request = URLRequest(url: url)
let task = URLSession.shared.dataTask(with: request) { (data, response, error) in
// If error, exits the program
guard error == nil else { print(error as Any); return }
// typecast response to HTTPURLResponse so that we can access its property allHeaderFields a.k.a "headers"
guard let httpResponse = response as? HTTPURLResponse else { print("could not typecast to HTTPURLResponse"); return }
// typecast allHeaderFields to String: String Dictionary
guard let fields = httpResponse.allHeaderFields as? [String: String] else { print("Error with headers"); return }
// get your authorization token here
// it probably is in the headers
for (_, field) in fields.enumerated() {
// ACTIONS REQUIRED FROM YOU:
// do something here to match field's key so that you get the authorization token
print(field)
}
// Space Between Token and Cookie infos
for _ in 0...3 { print() }
// get your cookies here
let cookies = HTTPCookie.cookies(withResponseHeaderFields: fields, for: (response?.url)!)
// THESE ARE THE COOKIES THAT YOU WANT FROM THE WEBSITE THAT YOU VISITED ABOVE
for cookie in cookies {
print("name: \(cookie.name) value: \(cookie.value)")
}
}
task.resume()
}
func getCookiesAndAuthToken(_ url: URL?) {
guard let url else { return }
var request = URLRequest(url: url)
guard let fields = request.allHTTPHeaderFields else { print("Error with headers"); return }
// get your authorization token here
// it probably is in the headers
for (_, field) in fields.enumerated() {
// ACTIONS REQUIRED FROM YOU:
// do something here to match field's key so that you get the authorization token
print(field)
}
}
1条答案
按热度按时间zbdgwd5y1#
我自己也是个新手。让我试着帮你。
字符串
编辑
如果你想要一个类似Python库请求的请求-响应,那么上面的就是答案。也许你需要像下面这样的请求头?但不确定。
型