问题
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