Search code examples
iosjsonswift3alamofireobjectmapper

return array of object with Alamofire


In my app I am using AlamofireObjectMapper. I want to make a method that returns an array of objects. With the help of Alamofire I made a GET request, which gives the response as responseArray. With using void function array listOfType always has values. But when I use non-void function that should return array of object MedicineType, array listOfType is nil. So here is my code.

func getAll() -> [MedicineType] {
  var listOfTypes: [MedicineType]?;
  Alamofire.request(BASE_URL, method:.get)
      .responseArray(keyPath:"value") {(response: DataResponse<[MedicineType]>) in
         if let status = response.response?.statusCode {
             switch(status) {
                case 200:
                    guard response.result.isSuccess else {
                    //error handling
                       return
                    }
                    listOfTypes = response.result.value;
                default:
                    log.error("Error", status);
              }
           }
        }
   return listOfTypes!;
}

Solution

  • As i said in my comment, you need to do this in closure, instead of return it, because your call for Alamofire is async so your response will be async

    This is an example, you need to add your error handle

        func getAll(fishedCallback:(_ medicineTypes:[MedicineType]?)->Void){
            var listOfTypes: [MedicineType]?;
            Alamofire.request(BASE_URL, method:.get)
                .responseArray(keyPath:"value") {(response: DataResponse<[MedicineType]>) in
                    if let status = response.response?.statusCode {
                        switch(status) {
                        case 200:
                            guard response.result.isSuccess else {
                                //error handling
                                return
                            }
                            finishedCallback(response.result.value as! [MedicineType])
                        default:
                            log.error("Error", status);
                                finishedCallback(nil)
                        }
                    }
            }
        }
    

    Use it

        classObject.getAll { (arrayOfMedicines) in
            debugPrint(arrayOfMedicines) //do whatever you need
        }
    

    Hope this helps