首页 > 解决方案 > 具有异步任务的 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:我还有其他任务,我只是减少了我的代码

标签: swiftconcurrencydispatch

解决方案


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)
}

推荐阅读