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



我正试图从以下代码中获取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))
}
}
}

最新更新