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

如何使用Alamofire在Swift 5(iOS应用程序)中获得http请求的结果?,ios,json,swift,alamofire,Ios,Json,Swift,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-

我试图从以下代码中获取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(“使用响应JSON\(JSON)验证成功)”函数
打印JSON文件时,它会正确打印。
我甚至尝试使用
print(“Validation successfully 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))
        }
    }
}
public func performRequest(参数:[String,String],完成:@escaping(Result)->Void){
var headers=HTTPHeaders(参数)
headers.add(名称:“内容类型”,值:“application/x-www-form-urlencoded;charset=UTF-8”)
AF.request(urlenpointapp,方法:.post,参数:参数,编码:URLEncoding.httpBody,头:头)。validate().responseJSON{response in
开关响应。结果{
case.success(let JSON)://将JSON文件存储在JSON变量中
//JSON文件打印正确
打印(“验证成功,响应JSON\(JSON)”)
//此变量在此函数外被视为nil(即使在返回时也是如此)
完成(.success(JSON))
案例。失败(let错误):
打印(“请求失败,错误\(error)”)
完成(.failure(error))
}
}
}

您缺少异步概念。使用闭包来管理它,而不是返回值。考虑不使用ALAMOFE,并学习如何在Swift中使用闭包。当使用新的Combine框架时,它特别容易。