簡體   English   中英

Swift將http請求響應作為數組

[英]Swift make a http request response as array

我有這個迅速的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
)

我對此代碼的響應是數組。但是當我嘗試將響應視為數組時,它給我一個錯誤。如何將響應轉換為數組,以便可以執行此response[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")
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM