How to return value from Alamofire

前端 未结 5 2049
忘掉有多难
忘掉有多难 2020-11-22 02:41

I am making url calls thru an API that I created using swift as follows:

class API {

  let apiEndPoint = \"endpoint\"
  let apiUrl:String!
  let consumerKey         


        
5条回答
  •  梦谈多话
    2020-11-22 03:20

    As mattt points out, Alamofire is returning data asynchronously via a “completion handler” pattern, so you must do the same. You cannot just return the value immediately, but you instead want to change your method to not return anything, but instead use a completion handler closure pattern.

    Nowadays, that might look like:

    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
    //
    

提交回复
热议问题