sakoaskoaso sakoaskoaso - 2 years ago 81
iOS Question

Swift make a http request response as array

I have got this swift http request

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

let responseString = String(data: data, encoding: .utf8)

Reponse string:

[0] => 1
[1] => Murad

And my response to this code is array.But when i try to treat response as array it gives me an error.How can i turn response into array so i can do this

Answer Source

Your result is most likely coming in as a JSON object, so you need to deserialize it before you can use the results.

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")
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download