gpt4 book ai didi

ios - 等待一个 block 加载,然后再加载更多

转载 作者:搜寻专家 更新时间:2023-10-30 22:14:55 25 4
gpt4 key购买 nike

我正在构建一个应用程序,我需要在其中分 block 加载数据,我的意思是先加载 5 个项目,然后继续加载另外 5 个,但我不知道该怎么做。目前我整理了我的项目列表,所以我得到了一个列表列表,每个列表有 5 个项目。现在,for 循环刚刚触发请求,但我想等待响应,然后在 for 循环中继续。

我使用 alamofire,我的代码如下所示。

private func requestItemsForField(items: [Item], completion: @escaping (_ measurements: Array<Measurement>?, _ success: Bool) -> ()) {
let userPackageId = UserManager.instance.selectedUserPackage.id
let params = ["userPackageId": userPackageId]

for field in fields {
let url = apiURL + "images/\(field.id)"

let queue = DispatchQueue(label: "com.response-queue", qos: .utility, attributes: [.concurrent])
Alamofire.request(url, method: .get, parameters: params, headers: headers()).responseArray(queue: queue, completionHandler: { (response: DataResponse<[Item]>) in

if let items = response.result.value as [Item]? {
NotificationCenter.default.post(name: NSNotification.Name(rawValue: "itemsLoadedNotification"), object: nil)
completion(items, true)
}
else {
print("Request failed with error: \(response.result.error)")
completion(nil, false)
}
})
}
}

这是我整理列表并将其传递给上面的地方。

 private func fetchAllMeasurements(completion: @escaping (_ measurements: [Item]?, _ done: Bool) -> ()) {
let fieldSet = FieldStore.instance.data.keys
var fieldKeys = [Item]()

for field in fieldSet {
fieldKeys.append(field)
}

// Create chunks of fields to load
let fieldChunks = fieldKeys.chunkify(by: 5)

var measurementsAll = [Measurement]()
for fields in fieldChunks {
requestItemsForField(fields: fields, completion: { (measurements, success) in
if let currentMeasurement = measurements {
measurementsAll.append(contentsOf: currentMeasurement)
}
completion(measurementsAll, true)
}
})
}
}

最佳答案

您需要根据您的请求获得您将拥有的测量数量(例如服务器有 34 个测量),然后编写类似的代码

var serverMeasurementsCount = 1 //should be for first request

func requestData() {
if self.measurements.count < self.serverMeasurementsCount {
...requestdata { data in
self.serverMeasurementsCount = data["serverMeasurementsCount"]
self.measurements.append(..yourData)
self.requestData()
}
}

或者不在completion handler或其他地方调用requestData

编辑:稍微修正了代码(serverMeasurementsCount = 1)

关于ios - 等待一个 block 加载,然后再加载更多,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42728074/

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