如何从Alamofire回报价值

如何从Alamofire回报价值,第1张

如何从Alamofire回报价值

正如mattt指出的那样,Alamofire通过“完成处理程序模式异步返回数据,因此您必须执行相同的 *** 作。您不能只是

return
立即获取值,而是要更改方法以不返回任何内容,而要使用完成处理程序关闭模式。

如今,它可能看起来像:

func getOrders(completionHandler: @escaping (Result<[String: Any]>) -> Void) {    performRequest("orders", completion: completionHandler)}func performRequest(_ section: String, completion: @escaping (Result<[String: Any]>) -> Void) {    let url = baseURL.appendingPathComponent(section)    let params = ["consumer_key": "key", "consumer_secret": "secret"]    Alamofire.request(url, parameters: params)        .authenticate(user: consumerKey, password: consumerSecret)        .responseJSON { response in switch response.result { case .success(let value as [String: Any]):     completion(.success(value)) case .failure(let error):     completion(.failure(error)) default:     fatalError("received non-dictionary JSON response") }    }}

Then, when you want to call it, you use this

completion
closure parameter
(in trailing closure, if you want):

api.getOrders { result in    switch result {    case .failure(let error):        print(error)    case .success(let value):        // use `value` here    }}// but don't try to use the `error` or `value`, as the above closure// has not yet been called//


欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/zaji/5622429.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-12-15
下一篇 2022-12-15

发表评论

登录后才能评论

评论列表(0条)

保存