代码之家  ›  专栏  ›  技术社区  ›  keverly

调度组不允许执行alamofire请求

  •  0
  • keverly  · 技术社区  · 6 年前

    我正在使用DispatchGroup等待我的一个函数的回调执行,然后继续在这个函数中,我调用alamo fire get request。我的问题出现在我引入DispatchGroup时,AlamoFire闭包永远不会被执行。

    样品

    let group = DispatchGroup()
    
    group.enter()
    Networking.getInfo(userID: userID) { info in
        group.leave()
    }
    
    group.wait()
    

    Networking 班级:

    static func getInfo(userID: Int, completion: @escaping(_ info: String) -> Void) {
        // Program reaches here
        Alamofire.request("https://someurl.com").responseJSON { response in
            // Program does NOT get here
            if let json = response.result.value {
                completion("Successful request")
            } else {
                completion("Some Error")
            }
        }
    }
    

    当我不使用调度组时,它工作得很好当我使用DispatchGroup时, getInfo 函数启动,但Alamo菲尔请求的关闭永远不会执行。

    2 回复  |  直到 6 年前
        1
  •  0
  •   drekka    6 年前

    我不确定自己是否正确,但我怀疑alamofire响应正在该组已挂起的同一队列(main)(wait())上排队。因为队列被挂起,所以永远不会执行完成闭包。

    手动编写这样的异步代码可能非常棘手我的建议是使用任何一个异步库来帮助解决这个问题我个人最喜欢的东西 PromiseKit 它还具有支持alamofire的特定扩展。像这样的项目可以消除异步代码的许多头痛。他们可能需要一些时间让你了解他们的模式,但这是值得做的。

        2
  •  0
  •   Faruk Hossain    6 年前

    我也面临同样的问题在这种情况下,我使用urlsession请求来利用它。此API使您的应用程序能够在应用程序未运行时执行后台下载,或者在iOS中,在应用程序挂起时执行后台下载。 https://developer.apple.com/documentation/foundation/urlsession

    let request = try URLRequest(url: url, method: .get, headers: headers)
    Alamofire.request(request) { response in
        ...
        ...
    }
    

    我把它改成这样:

    let request = try URLRequest(url: url, method: .get, headers: headers)
    let task = URLSession.shared.dataTask(with: request) { (data, response, error) in
        ...
        ...
    }
    task.resume()
    

    然后它工作得很好。