Issue getting count of records in JSON array using Alamofire | Swift 5

Viewed 274

Essentially I have the following function:

func stagedCount() {
         let url = "example.com"
         let parameters: Parameters =
         ["person": "\(name)"]
         Alamofire.request(url, method: .post, parameters: parameters).responseData(completionHandler : { response in
             if let allObjects = response.result.value as? NSArray{
              print("Array length is \(allObjects.count)")
         }
     }
 )}

The JSON response from the URL looks like this:

[
  {
    "person": "Jake",
    "hobby": "soccer"
  },
  {
    "person": "Mary",
    "hobby": "surfing"
  }
]

I am getting the following response and no count is currently printing.

Cast from 'Data?' to unrelated type 'NSArray' always fails

How can I fix this to get a count of the amount of records in the array? The result I am looking for is 2

1 Answers

The error is pretty clear. responseData will return a JSON String data. You can not convert Data to an Array. What you need is to decode your json data into an array of person structures:

struct Person {
    let person: String
    let hobby: String
}

when decoding the response:

guard 
   let data = response.data, 
   let json = String(data: data, encoding: .utf8) 
else { return }
print("json:", json)
do {
    let people = try JSONDecoder().decode([Person].self, from: data)
    print(people.count)
    for person in people {
        print(person)
    }
} catch { 
    print(error) 
}            
Related