gpt4 book ai didi

json - 如何使用 Swift 从 NSURLSession 获取 cookie?

转载 作者:IT老高 更新时间:2023-10-28 12:52:43 29 4
gpt4 key购买 nike

我有一个 NSURLSession 调用 dataTaskWithRequest 以便以这种方式发送 POST 请求

func makeRequest(parameters: String, url:String){
var postData:NSData = parameters.dataUsingEncoding(NSASCIIStringEncoding)!
var postLength:NSString = String(postData.length )
var request = NSMutableURLRequest(URL: NSURL(string: url)!)
var session = NSURLSession.sharedSession()
request.HTTPMethod = "POST"

var error:NSError?
//request.HTTPBody = NSJSONSerialization.dataWithJSONObject(postData, options: nil, error: &error)
request.HTTPBody = postData
request.setValue(postLength, forHTTPHeaderField: "Content-Length")
request.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")
request.setValue("application/json", forHTTPHeaderField: "Accept")

var task = session.dataTaskWithRequest(request, completionHandler: { (data, response, error) -> Void in

println("Response:\(response)")

// Other stuff goes here

})

响应等于:

<NSHTTPURLResponse: 0x7fcd205d0a00> { URL: http://XXX.XXX.XXX:0000/*** } { status code: 200, headers {
"Cache-Control" = "no-store, no-cache, must-revalidate, post-check=0, pre-check=0";
Connection = close;
"Content-Length" = 16;
"Content-Type" = "application/json; charset=utf-8";
Date = "Mon, 13 Apr 2015 00:07:29 GMT";
Expires = "Thu, 19 Nov 1981 08:52:00 GMT";
Pragma = "no-cache";
Server = "Apache/2.2.15 (CentOS)";
"Set-Cookie" = "MYCOOKIEIS=12dsada342fdshsve4lorewcwd234; path=/";
"X-Powered-By" = "PHP/5.3.14 ZendServer/5.0";
} }

我的问题是我不知道如何获取“Set-Cookie”中名为 MYCOOKIEIS 的 cookie。

我将在用户登录时使用它,所以如果用户未登录 -> 登录(调用登录 api)否则转到主屏幕并调用其他 API。

有人可以帮我把 cookie 拿出来吗?

我找到了 answer但它是在 Objective-C 中的,我不知道如何用 Swift 来做

最佳答案

Swift 版本可能类似于:

let task = session.dataTask(with: request) { data, response, error in
guard
let url = response?.url,
let httpResponse = response as? HTTPURLResponse,
let fields = httpResponse.allHeaderFields as? [String: String]
else { return }

let cookies = HTTPCookie.cookies(withResponseHeaderFields: fields, for: url)
HTTPCookieStorage.shared.setCookies(cookies, for: url, mainDocumentURL: nil)
for cookie in cookies {
var cookieProperties = [HTTPCookiePropertyKey: Any]()
cookieProperties[.name] = cookie.name
cookieProperties[.value] = cookie.value
cookieProperties[.domain] = cookie.domain
cookieProperties[.path] = cookie.path
cookieProperties[.version] = cookie.version
cookieProperties[.expires] = Date().addingTimeInterval(31536000)

let newCookie = HTTPCookie(properties: cookieProperties)
HTTPCookieStorage.shared.setCookie(newCookie!)

print("name: \(cookie.name) value: \(cookie.value)")
}
}
task.resume()

关于json - 如何使用 Swift 从 NSURLSession 获取 cookie?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29596206/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com