ios - 使用 Alamofire 返回对象数组

标签 ios json swift3 alamofire objectmapper

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

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

最佳答案

正如我在评论中所说,您需要在闭包中执行此操作,而不是返回它,因为您对 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
    }

希望对你有帮助

关于ios - 使用 Alamofire 返回对象数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45466651/

相关文章:

ios - 如何只重绘一个特定的图层? (IOS,SWIFT)

ios - 使用导航 Controller 在 View 之间循环

ios - Swift 3 在没有 Storyboard 的情况下实现 SideMenu 控件(硬编码)

javascript - 将包含变量名称的类似数组的字符串解析为数组

json - 带有对象的 Jade/Pug JSON 插值

arrays - 无论索引如何,检查两个数组中的元素是否相同

ios - 在没有 `invalidateLayout` 跳转的情况下自动调整 UICollectionViewLayout(支持 iOS 9)中的单元格

javascript - 占位符上的 Node 、表达和请求显示批处理\n

ios - 在 UITabBarController 中自定义更多选项卡

ios - 使用 SwifyStoreKit 在应用内购买无法获取有关产品的信息