Code after DispatchGroup().wait() never called

送分小仙女□ 提交于 2019-12-25 02:27:10

问题


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

Here is the code:

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
}

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.


回答1:


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.

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


来源:https://stackoverflow.com/questions/52149718/code-after-dispatchgroup-wait-never-called

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!