我已经在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 回应:但为什么不带着我的密码来呢
1条答案
按热度按时间oxalkeyp1#
使用以下示例代码,其中我将
headers
更改为[:]
而不是["" : ""]
,并添加了一个结构体来解码post响应。注意
responseJSON
已过时。像这样使用它: