简体   繁体   English

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

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

I'm trying to get the resilt of an http request (a JSON file) from the following code:我正在尝试从以下代码中获取 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
}

The problem is that, when I print the JSON file from the print("Validation Successful with response JSON \\(JSON)") function, it gets printed correclty.问题是,当我从print("Validation Successful with response JSON \\(JSON)")函数打印 JSON 文件时,它会正确打印。 I even tried to print the variable any inside of the block using print("Validation Successful with response JSON \\(any)") and it works, but when it gets returned, its value is nil .我什至尝试使用print("Validation Successful with response JSON \\(any)")块内的任何变量,它可以工作,但是当它返回时,它的值为nil

You are using an asynchronous method, so it means you get the result after some time.您正在使用异步方法,因此这意味着您会一段时间获得结果。

You should change your method to你应该改变你的方法

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