gpt4 book ai didi

ios - 从 Alamofire 响应访问 JSON 值

转载 作者:行者123 更新时间:2023-11-28 10:50:14 24 4
gpt4 key购买 nike

我正在向返回以下 JSON 的本地服务器发出请求:

{"session_key":"somecodexyz1234"}

以下代码用于尝试打印 session_key 值。但这总是被评估为nil`。

Alamofire.request(url, method: .post, parameters: parameters).responseJSON(completionHandler: {
response in
print("Request: \(String(describing: response.request))")
print("Response: \(String(describing: response.response))")

print("Response code: \(String(describing: response.response?.statusCode))")


if let data = response.data, let utf8Text = String(data: data, encoding: .utf8) {
print("Data: \(utf8Text)") // original server data as UTF8 string
}}

if response.data != nil {
let json = JSON(data: response.data!)

// changes
if let arr : NSArray = json as? NSArray
{
let sk = arr.value(forKey: "session_key") as? String
if sk != nil {print(sk)}
}
}

以下是输出(print(sk) 没有执行,因为它是 nil):

Request: Optional(http://127.0.0.1:5000/code)
Response: Optional(<NSHTTPURLResponse: 0x60800023f260> { URL: http://127.0.0.1:5000/code } { status code: 200, headers {
"Content-Length" = 40;
"Content-Type" = "application/json";
Date = "Sat, 23 Sep 2017 06:02:25 GMT";
Server = "Werkzeug/0.12.2 Python/3.4.3";
} })
Response code: Optional(200)
Data: "{\"session_key\":\"somecodexyz1234\"}"

最佳答案

使用下面的代码从 json 中的 almofire 获取响应。在您的代码中,您直接检查 response.data 而不是首先检查 response.result,如下所示。

Alamofire.request(requestURL, method:.post, parameters: param as? Parameters, encoding: URLEncoding(destination: .httpBody), headers: headers).responseJSON(completionHandler: { (response) in
switch response.result
{
case .success(let responseJSON):
// If request success then you will get response in json here
if responseJSON is String{
print("Reponse is string")
}
else if responseJSON is NSDictionary{
print("Reponse is Dictionary")
}
else if responseJSON is NSArray{
print("Reponse is Array")
}
else{
print("Any object")
return
}
print("Response : \((dicResponse)")

break
case .failure(let error):
// If request is failure then got error here.
break
}
})

关于ios - 从 Alamofire 响应访问 JSON 值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46376637/

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