gpt4 book ai didi

swift - 如何在 Swift 中存储 JSON 发布响应的一个特定元素

转载 作者:行者123 更新时间:2023-11-30 11:50:03 25 4
gpt4 key购买 nike

我有一个快速程序,可以创建一个成功的 JSON 帖子到 Rails 应用程序。这是回复:

Optional(<NSHTTPURLResponse: 0x604000226280> { URL: http://groupsyncenv.rtimfc7m2.eu-west-1.elasticbeanstalk.com/login_post } { Status Code: 200, Headers {
"Cache-Control" = (
"max-age=0, private, must-revalidate"
);
Connection = (
close
);
"Content-Length" = (
618
);
"Content-Type" = (
"application/json; charset=utf-8"
);
Date = (
"Wed, 24 Jan 2018 17:57:52 GMT"
);
Etag = (
"W/\"c34b1ba0f3cfbd53ef65a30eddd47c50\""
);
Server = (
"nginx/1.12.1"
);
Via = (
"1.1 m00180A4E4E3C (squid/3.5.23)"
);
"X-Cache" = (
"MISS from m00180A4E4E3C"
);
"X-Cache-Lookup" = (
"MISS from m00180A4E4E3C:3128"
);
"X-Content-Type-Options" = (
nosniff
);
"X-Frame-Options" = (
SAMEORIGIN
);
"X-Request-Id" = (
"9bf3c1fa-e362-4d59-8396-8540981f1d36"
);
"X-Runtime" = (
"0.092878"
);
"X-XSS-Protection" = (
"1; mode=block"
);

我从这段代码中需要的只是与响应“X-Request-Id”关联的数字,但我不知道该怎么做。我的快速程序如下:

func loginPost(){

let headers = [
"Content-Type": "application/json",
"Cache-Control": "no-cache",
"Postman-Token": "b5468cec-292a-6c60-d195-6e270909e54b"
]
let parameters = [
"email": "sample@email.com",
"password": "password123"
] as [String : Any]

let postData = try? JSONSerialization.data(withJSONObject: parameters, options: [])
guard let data = postData else {
return
}

let request = NSMutableURLRequest(url: NSURL(string: "http://groupsyncenv.rtimfc7um2.eu-west-1.elasticbeanstalk.com/login_post")! as URL,
cachePolicy: .useProtocolCachePolicy,
timeoutInterval: 10.0)
request.httpMethod = "POST"
request.allHTTPHeaderFields = headers
request.httpBody = postData as? Data

let session = URLSession.shared
let dataTask = session.dataTask(with: request as URLRequest, completionHandler: { (data, response, error) -> Void in
if (error != nil) {
print(error)
} else {
let httpResponse = response as? HTTPURLResponse
print(httpResponse)
}
})

dataTask.resume()

}

如您所见,我只是打印了 Http 响应,我知道这是错误的,但我不知道如何访问此处的各个元素。预先感谢您的帮助!

最佳答案

通过调用 response.allHeaderFields(它是一个 )将 URLResponse 对象转换为 HTTPURLResponse 后,您可以简单地访问 HTTP header 字典,因此您可以使用订阅来获取特定键对应的值。

一些通用建议:不要使用旧的 Foundation 数据类型,除非您有充分的理由这样做。使用他们的原生 Swift 替代品。当您在创建 Foundation 对象后立即将它们转换为其 Swift 替代方案时尤其如此,因为 Swift API 需要 Swift 类型,例如 URLRequest 而不是 NSMutableURLRequestURL 而不是 NSURL

let headers = [
"Content-Type": "application/json",
"Cache-Control": "no-cache"
]
let parameters = [
"email": "sample@email.com",
"password": "password123"
] as [String : Any]

let postData = try? JSONSerialization.data(withJSONObject: parameters, options: [])

var request = URLRequest(url: URL(string: "http://groupsyncenv.rtimfc7um2.eu-west-1.elasticbeanstalk.com/login_post")!, cachePolicy: .useProtocolCachePolicy, timeoutInterval: 10.0)
request.httpMethod = "POST"
request.allHTTPHeaderFields = headers
request.httpBody = postData

URLSession.shared.dataTask(with: request, completionHandler: { data, response, error in
if (error != nil) {
print(error!)
} else if let response = response as? HTTPURLResponse {
let requestId = response.allHeaderFields["X-Request-Id"] as? String
print(requestId)
}
}).resume()

关于swift - 如何在 Swift 中存储 JSON 发布响应的一个特定元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48428994/

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