簡體   English   中英

如何使用 Alamofire 在 Swift 5(iOS 應用程序)中獲取 http 請求的結果?

[英]How do I get the result of an http request in Swift 5 (iOS app) using Alamofire?

我正在嘗試從以下代碼中獲取 http 請求(一個 JSON 文件)的 resilt:

public func performRequest(parameters: [String, String]) -> Any{
    var headers = HTTPHeaders(parameters)
    headers.add(name: "Content-Type", value: "application/x-www-form-urlencoded; charset=UTF-8")
    
    var any : Any?
    
    AF.request(urlEndPointApp, method: .post, parameters: parameters, encoding: URLEncoding.httpBody,  headers: headers).validate().responseJSON{ response in
        switch response.result {
        case .success(let JSON): // stores the json file in JSON variable
            // the JSON file is printed correctly
            print("Validation Successful with response JSON \(JSON)")
            // this variable is seen as nil outside this function (even in return)
            any = JSON
        case .failure(let error):
        print("Request failed with error \(error)")
        }
    }
    
    return any
}

問題是,當我從print("Validation Successful with response JSON \\(JSON)")函數打印 JSON 文件時,它會正確打印。 我什至嘗試使用print("Validation Successful with response JSON \\(any)")塊內的任何變量,它可以工作,但是當它返回時,它的值為nil

您正在使用異步方法,因此這意味着您會一段時間獲得結果。

你應該改變你的方法

public func performRequest(parameters: [String, String], completion: @escaping (Result<Any, Error>) -> Void) {
    var headers = HTTPHeaders(parameters)
    headers.add(name: "Content-Type", value: "application/x-www-form-urlencoded; charset=UTF-8")
    
    AF.request(urlEndPointApp, method: .post, parameters: parameters, encoding: URLEncoding.httpBody,  headers: headers).validate().responseJSON{ response in
        switch response.result {
        case .success(let JSON): // stores the json file in JSON variable
            // the JSON file is printed correctly
            print("Validation Successful with response JSON \(JSON)")
            // this variable is seen as nil outside this function (even in return)
            completion(.success(JSON))
        case .failure(let error):
            print("Request failed with error \(error)")
            completion(.failure(error))
        }
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM