【发布时间】:2018-01-10 00:32:08
【问题描述】:
在我的应用程序中,我使用的是 AlamofireObjectMapper。
我想创建一个返回对象数组的方法。在 Alamofire 的帮助下,我发出了一个 GET 请求,它以 responseArray 的形式给出响应。
使用 void 函数数组 listOfType 总是有值。
但是当我使用应该返回对象数组MedicineType 的非void 函数时,数组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!;
}
【问题讨论】:
-
您需要在关闭时执行此操作,而不是返回它,因为您对 Alamofire 的调用是异步的,因此您的响应将是异步的
-
寻找“Swift + Closure + Async”。如果你仔细检查,
return listOfTypes!;应该被称为listOfTypes = response.result.value;之前(可以添加打印)
标签: ios json swift3 alamofire objectmapper