gpt4 book ai didi

ios - 使用 Alamofire 返回对象数组

转载 作者:塔克拉玛干 更新时间:2023-11-02 08:11:35 26 4
gpt4 key购买 nike

在我的应用程序中,我使用的是 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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com