如何使用 Alamofire 在 Swift 5(iOS 应用程序)中获取 http 请求的结果?

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

我正在尝试通过以下代码获取 http 请求(JSON 文件)的结果:

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))
        }
    }
}