gpt4 book ai didi

ios - Swift 将 http 请求响应作为数组

转载 作者:搜寻专家 更新时间:2023-11-01 07:10:21 25 4
gpt4 key购买 nike

我有这个快速的 http 请求

    var request = URLRequest(url: URL(string: "http://www.web.com/ajax/logreg.php")!)
request.httpMethod = "POST"
let pass = pass_text_field.text!.addingPercentEncoding(withAllowedCharacters: .queryValueAllowed)!
let postString = "app_reg_pass=\(pass)"
request.httpBody = postString.data(using: .utf8)
let task = URLSession.shared.dataTask(with: request) { data, response, error in
guard let data = data, error == nil else {
print("error=\(error!)")
return
}
if let httpStatus = response as? HTTPURLResponse, httpStatus.statusCode != 200 { print("statusCode should be 200, but is \(httpStatus.statusCode)")
print(response!)
}

let responseString = String(data: data, encoding: .utf8)
print(responseString!)
}
task.resume()

响应字符串:

Array
(
[0] => 1
[1] => Murad
)

我对此代码的响应是数组。但是当我尝试将响应视为数组时,它给了我一个错误。我怎样才能将响应转换为数组,这样我才能做到这一点响应[0]?

最佳答案

您的结果很可能以 JSON 对象的形式出现,因此您需要先对其进行反序列化,然后才能使用结果。

do {
let jsonData = try JSONSerialization.jsonObject(with: data, options: .mutableContainers) as! [Any]

print(jsonData[0] as! Int) // should print "1"
print(jsonData[1] as! String) // should print "Murad"

} catch {
print("An error occurred")
}

关于ios - Swift 将 http 请求响应作为数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45353154/

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