swift - 具有异步任务的 DispatchGroup
问题描述
enter code here
我在调度组尝试了很多事情,但我无法获得稳定的结果。从我的服务器开始,我使用 Alamofire 获取数据。我在 Helper Class 中编写了一个函数,并在 AppDelegate.swift 中使用了这个函数。
我不知道是在调用函数时将调度组放在 AppDelegate 中,还是仅将调度组放在 Helper Class 中的函数中。
func alomofireGet(URL: String, onCompletion:@escaping ((JSON) -> Void)) {
// let group = DispatchGroup()
var contentJSON = JSON()
// group.enter()
Alamofire.request(URL, method: .get).responseJSON() { (reponse) in
if reponse.result.isSuccess {
contentJSON = JSON(reponse.result.value!)
} else {
contentJSON = JSON(reponse.result.error!)
}
// group.leave()
}
// group.notify(queue: .main) {
onCompletion(contentJSON)
}
在 App 委托中,我编写了一个函数,该函数在我的类中调用该函数。
func connect() {
let group = DispatchGroup()
let _: Bool = KeychainWrapper.standard.removeObject(forKey: "token")
var token = String()
group.enter()
Helper().alomofireGet(URL: "http://192.168.1.19/app_dev.php/login/app") { contenuJSON in
token = contenuJSON["csrfToken"].stringValue
group.leave()
}
group.notify(queue: .main) {
let _: Bool = KeychainWrapper.standard.set(token, forKey: "token")
let t: String? = KeychainWrapper.standard.string(forKey: "token")
print(t!)
}
}
问题是变量“t”为空。当我在应用程序委托中调用 keychainWrapper 时,钥匙串也是空的。
PS:我还有其他任务,我只是减少了我的代码
解决方案
func alomofireGet(URL: String, onCompletion:@escaping ((JSON) -> Void)) {
// let group = DispatchGroup()
var contentJSON = JSON()
// group.enter()
Alamofire.request(URL, method: .get).responseJSON() { (reponse) in
if reponse.result.isSuccess {
contentJSON = JSON(reponse.result.value!)
} else {
contentJSON = JSON(reponse.result.error!)
}
// group.leave()
}
// group.notify(queue: .main) {// where you call wait()function. This blocks the current thread until the group’s tasks have completed.
onCompletion(contentJSON)
}
推荐阅读
- c# - 从 Unity 构建中恢复检查器值
- node.js - 如何从 NodeJS 调用 FastAPI 路由?
- r - 在 R 中使用过滤器功能。需要为赛马数据库分配 NA 并保持数据集的长度相同
- amazon-web-services - AWS ECS 实例缺少“ecs.capability.efsAuth”属性
- laravel - 是否可以在 laravel 7.x 中使用 create-react-app
- c# - Word OpenXML 目录中的行数可以确定吗
- codenameone - 如何使用选择器创建一个弹出窗口,其中选择器立即处于活动状态并带有“跳过”选项?
- c# - 如何在两个 HierarchicalDataTemplates 中间添加一个 TreeViewItem?
- winapi - IMFTransform 配置
- reactjs - 如何在 React (google-map-react) 中获取 dragend 上的标记位置