2017-08-02 109 views
3

在我的应用程序中,我使用AlamofireObjectMapper。 我想做一个返回对象数组的方法。在Alamofire的帮助下,我做了一个GET请求,它将响应作为responseArray。 使用void函数数组listOfType始终有值。 但是当我使用非void函数应该返回对象数组MedicineType,数组listOfType为零。 所以这里是我的代码。返回Alamofire对象数组

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

你需要这样做的关闭,而不是回报,因为你的呼吁Alamofire是异步所以你的反应将是异步 –

+0

看为“Swift + Closure + Async”。如果仔细检查,'listOfTypes!;'应该被调用BEFORE'listOfTypes = response.result.value;'(你可以添加打印) – Larme

回答

2

正如我在我的评论说,你需要做到这一点的关闭,而不是回报,因为你的呼吁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 
    } 

希望这有助于

+0

@vadian再次编辑,感谢两次 –

+1

再次感谢,你帮了我很多。 –

0

尝试关闭

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

      } 
     } 
    } 

}