永远不会调用DispatchGroup()。wait()之后的代码 [英] Code after DispatchGroup().wait() never called

查看:77
本文介绍了永远不会调用DispatchGroup()。wait()之后的代码的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使对服务的调用同步,因为我想让我的调用返回已经使用泛型映射的对象。

I want to make my call to the service synchronous because I want my call to return my object already mapped with generics.

下面是代码:

func execute<T: Mappable>(request: HttpRequest, responseType: T.Type) throws -> T? {
    var responseObject: T?
    let group = DispatchGroup()
    group.enter()

    Alamofire.SessionManager.default.request(request.stringURL, method: request.method, parameters: request.parameter.toJSON(), encoding: request.encoding, headers: request.headers)
        .validate()
        .response(completionHandler: { response in
            responseObject = self.singleResult(dataResult: response.data, resultType: T.self)
            group.leave()
    })

    group.wait()

    guard let response = responseObject else {
        return nil
    }

    return response
}

问题在于,从未调用group.wait()下的代码,但通过Charles我可以看到请求正在运行并且已经结束。

The problem is that the code under group.wait() is never called but with Charles I can see that the request is working and have ended.

推荐答案

我建议 PromiseKit 为您提供更多控制权处理异步的代码。使用 PromiseKit ,您将能够以与上述相同的方式访问对象。

I would recommend PromiseKit to give you more control on handling asynchronous code. Using PromiseKit, you will be able to access the object in the same way you are trying above.

如果您不想添加依赖项,则可以使用下面的 completion handler 来获取对象当请求结束时。

If you don't want to add dependency then you can use the completion handler as below to get the object when request is ended.

func execute<T: Mappable>(request: HttpRequest, responseType: T.Type, completion: @escaping ((T?) -> Void)) {
        Alamofire.SessionManager.default.request(request.stringURL, method: request.method, parameters: request.parameter.toJSON(), encoding: request.encoding, headers: request.headers)
            .validate()
            .response(completionHandler: { response in
                let mappedObject: T? = self.singleResult(dataResult: response.data, resultType: T.self)
                completion(mappedObject)
            })
} 

然后您可以调用以下方法,

Then you can call the method as below,

let service = YourService()
service.execute(request: fetchUser, responseType: User.self) { user in
            guard let user = user else { return }
            print(user.name)
        }

这篇关于永远不会调用DispatchGroup()。wait()之后的代码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆