【发布时间】:2021-09-08 08:13:52
【问题描述】:
我正在从 API 下载一些 JSON,但在我们进入下一个屏幕之前,必须完成另一个先决条件(动画)。
我决定使用DispatchGroup 来执行此操作,但也需要重新加载。
我想出了一个使用完成处理程序的解决方案,它要么是dispatchGroup.leave,要么只是移动到下一个屏幕,因为我们只需要下载一次数据。
let dispatchGroup = DispatchGroup()
var userName: String?
func fetchData() {
dispatchGroup.enter()
dispatchGroup.enter()
resolveDataRequirements(dispatchGroup.leave)
dispatchGroup.notify(queue: .main) { [weak self] in
self?.moveToNextScreen()
}
}
func resolveDataRequirements(_ completion: @escaping(() -> Void)) {
api.resolve { [weak self] result in
switch result {
case .success(let user):
self?.userName = user
completion()
case .failure:
break
}
}
}
func moveToNextScreen() {
// move to next screen, but passes the user
}
// reload data, and once the data is downloaded move to next screen
func reloadData() {
resolveDataRequirements(moveToNextScreen)
}
// the user might choose to fetch data
fetchData()
// now if the user wanted to reload
reloadData()
现在的问题是这是在视图模型中 - 所以用户字符串实际上是我希望根除的状态。
有什么方法可以将用户字符串传递给dispatchGroup.notify 或类似的?
【问题讨论】:
标签: swift dispatchgroup