我使用Alamofire和PromiseKit作为单独的Cocoapod安装。我可以使用Alamofire检索JSON数据,但是在配置PromiseKit时我收到以下错误。以下错误出现在“履行,拒绝”所在的行中。
错误消息:上下文关闭类型'(解析器< _>) - > Void'期望1个参数,但是在闭包体中使用了2个
我在模拟器中使用Xcode 9.2和IOS 11.2。提前感谢您的建议!
func wantToReturnAnArrayOfActor() -> Promise<[Actor]> {
return Promise { fulfill, reject in
Alamofire.request(ApiUrl.url.rawValue).responseJSON { (response) in
switch(response.result)
{
case .success(let responseString): print("my response string = \(responseString)")
let actorResponse = ActorApiResponse(JSONString: "\(responseString)")//converts all of the data into the ActorApiResponse model class
return when(fulfilled: actorResponse)
DispatchQueue.main.async {
print("actorResponse = \(String(describing: actorResponse))")
}
case .failure(let error): print("alamofire error = \(error)")
}
}
}
}
答案 0 :(得分:0)
它应该是这样吗,
func wantToReturnAnArrayOfActor() -> Promise<[Actor]> {
return Promise() { resolver in
Alamofire.request(ApiUrl.url.rawValue).responseJSON { (response) in
switch(response.result)
{
case .success(let responseObject):
let actorResponse = ActorApiResponse(jsonObject: responseObject)
let actors = actorResponse.getActors()
resolver.fulfill(actors)
case .failure(let error):
resolver.reject(error)
}
}
}
}
Promise的初始化器关闭采用单个参数,其类型为 Resolver ,这是您的错误所说的。然后,您希望在承诺执行完成时使用 [Actor] 类型的结果解析您的承诺,或者如果在执行期间发生错误则拒绝并出错。
这里有几点需要注意:
你可以拥有 ActorApiResponse 这样的东西,
struct ActorApiResponse {
init(jsonObject: Any) {
}
func getActors() -> [Actor] {
// calculate and return actors
return []
}
}
然后,您可以从其他地方调用它,
wantToReturnAnArrayOfActor().done {
// do something with [Actor here]
// You can also chain the multiple promise using .then instead of using done
}.catch { error in
print("Error occurred \(error)")
}