无法在swift中使用alamofire获取post API的JSON响应

z31licg0  于 2023-01-08  发布在  Swift
关注(0)|答案(1)|浏览(121)

我已经在NetworkManager中创建了泛型方法,但此serviceCall仅工作。如果我使用包含如下参数的post方法,则获取方法API

    • 错误:**
{
code = "-32700";
meaning = "Undefined array key \"params\"";
message = "Parse error";
}

func testServiceCall(){

let parameters = ["name": "testinggg", "job": "manager"] as [String : Any]

let request = RequestObject(params: parameters, method: .post, path: "https://reqres.in/api/users", isTokenNeed: false, vc: self)
WebService.sharedInstance.serviceCall(UserModel.self, with: request) { (response, error) in
    print("user post response \(response)")
    
}
}
    • 这是网络管理器类**:此处添加的参数不起作用
class GeneralResponse<T: Codable>: Codable {
    var jsonrpc: String
    var result: T?
    let error: ErrorClass?
}

struct ErrorClass: Codable {
    let code, message, meaning: String?
}

struct RequestObject {
    
    var params: [String: Any]?
    var method: HTTPMethod
    var path: String
    var isTokenNeed: Bool = false
    var vc: UIViewController?
}

class NetworkManager {

private let decoder: JSONDecoder
static let sharedInstance = NetworkManager()

public init(_ decoder: JSONDecoder = JSONDecoder()) {
    self.decoder = decoder
}

public func serviceCall<T: Codable>(_ objectType: T.Type,
                                    
                                    with request: RequestObject,
                                    completion: @escaping  (T?, Error?) -> Void)  {
    
    AF.request(request.path, method: request.method, parameters: request.params,encoding: JSONEncoding.default, headers: request.isTokenNeed ? ["Authorization" : "Bearer hnjjdshjdsh", "Accept": "application/json"] : ["" : ""])
        .responseJSON { response in
            
            switch response.result {
            case .success(_):
                do {
                    let data = response.data
                    let responseData  = try self.decoder.decode(T.self, from: data ?? Data())
                    completion(responseData, nil)
                    
                } catch {
                    completion(nil, error)
                    print("in catch \(error.localizedDescription)")
                }
            case .failure(let AFError):
                let error = AFError
                print(error.localizedDescription)
                print("failure error: \(error)")
            }
        }
}
}

Postman 回应:但为什么不带着我的密码来呢

oxalkeyp

oxalkeyp1#

使用以下示例代码,其中我将headers更改为[:]而不是["" : ""],并添加了一个结构体来解码post响应。
注意responseJSON已过时。

struct PostResponse: Codable {
    let job, name, id, createdAt: String
}

class NetworkManager {
    private let decoder: JSONDecoder
    static let sharedInstance = NetworkManager()
    
    public init(_ decoder: JSONDecoder = JSONDecoder()) {
        self.decoder = decoder
    }
    
    public func serviceCall<T: Codable>(_ objectType: T.Type,
                                        with request: RequestObject,
                                        completion: @escaping  (T?, Error?) -> Void)  {
        
        AF.request(request.path, method: request.method, parameters: request.params,encoding: JSONEncoding.default, headers: request.isTokenNeed ? ["Authorization" : "Bearer hnjjdshjdsh", "Accept": "application/json"] : [:])   // <-- here

            .responseJSON { response in

                switch response.result {
                case .success(_):
                    do {
                        let data = response.data
                        let responseData  = try self.decoder.decode(T, from: data ?? Data())  
                        completion(responseData, nil)
                    } catch {
                        print("in catch \(error)")
                        completion(nil, error)
                    }
                case .failure(let AFError):
                    let error = AFError
                    print(error.localizedDescription)
                    print("failure error: \(error)")
                }
            }
    }
}

像这样使用它:

let parameters = ["name": "testinggg", "job": "manager"]
let request = RequestObject(params: parameters, method: .post, path: "https://reqres.in/api/users", isTokenNeed: false)
NetworkManager.sharedInstance.serviceCall(PostResponse.self, with: request) { (response, error) in
    print("\n---> user post response \(response)")
}

相关问题