1

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]?

13
  • 1
    what is the error? Commented Jul 27, 2017 at 14:05
  • @pierreafranck Type 'URLResponse?' has no subscript members Commented Jul 27, 2017 at 14:05
  • @sakoaskoaso your response is in JSON format? Commented Jul 27, 2017 at 14:08
  • @ReinierMelian no just an array Commented Jul 27, 2017 at 14:09
  • 1
    If your webservice is in PHP you just have to replace output by echo json_encode($myArray) Commented Jul 27, 2017 at 14:13

1 Answer 1

2

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")
}
Sign up to request clarification or add additional context in comments.

4 Comments

Could not cast value of type '__NSArrayM' (0x1033a2a98) to 'NSDictionary' (0x1033a4208).
@sakoaskoaso try it now, I changed it to cast to an array instead of a dictionary
You have to cast result in Array of dictionary : let jsonData = try JSONSerialization.jsonObject(with: data, options: .mutableContainers) as! [[String: Int]]
Thanks for thy answer!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.