Swift将http请求响应作为数组

时间:2017-07-27 14:03:47

标签: ios swift

我有这个快速的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
)

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

1 个答案:

答案 0 :(得分:2)

您的结果很可能是作为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")
}