sakoaskoaso
sakoaskoaso

Reputation: 347

Swift make a http request response as array

I have got this swift http request

    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()

Reponse string:

Array
(
    [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 response[0]?

Upvotes: 1

Views: 1191

Answers (1)

Paolo
Paolo

Reputation: 3945

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")
}

Upvotes: 2

Related Questions