return 带有 Alamofire 的对象数组

return array of object with Alamofire

在我的应用程序中,我使用的是 AlamofireObjectMapper。 我想创建一个 return 对象数组的方法。在 Alamofire 的帮助下,我发出了一个 GET 请求,它以 responseArray 的形式给出了响应。 使用 void 函数数组 listOfType 总是有值。 但是当我使用应该 return 对象数组 MedicineType 的非空函数时,数组 listOfType 为零。 所以这是我的代码。

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!;
}

正如我在评论中所说,您需要在闭包中执行此操作,而不是 return,因为您对 Alamofire 的调用是异步的,因此您的响应将是异步的

这是一个示例,您需要添加您的错误句柄

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

使用它

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

希望对您有所帮助

尝试关闭

func getAll(_ callback :(medicineTypes:[MedicineType]?) -> Void) -> Void {
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;
                callback(listOfTypes)
            default:
                log.error("Error", status);
                 callback({})

          }
       }
    }

}