ios – URLSession.shared.dataTask returning arrays

[ad_1]

I’ve the next code

    URLSession.shared.dataTask(with: request) { knowledge, response, error in
        guard error == nil else {
            print("Error: error calling POST")
            completion(nil, error, nil)
            return
        }
        guard let knowledge = knowledge else {
            print("Error: Didn't obtain knowledge")
            return
        }
        guard let response = response as? HTTPURLResponse, (200 ..< 299) ~= response.statusCode else {
            print("Error: HTTP request failed")
            return
        }
        do {
            guard let jsonObject = attempt JSONSerialization.jsonObject(with: knowledge) as? [String: Any] else {
                return
            }
            completion(nil, nil, jsonObject)
        } catch {
            print("Error: Making an attempt to transform JSON knowledge to string")
            return
        }
    }.resume()

What if the API returns an array of objects? What if “knowledge” is an array? Will let jsonObject = attempt JSONSerialization.jsonObject(with: knowledge) as? [String: Any] be an array?

How do I alter the code to assist the API returning an json array and a json object?

[ad_2]

Leave a Reply