这是我的JSON结构和postman的响应
{
"jsonrpc": "2.0",
"result": {
"categories": [
{
"id": 91,
"title": "ADMINISTRATION & SECRETARIAL",
},
{
"id": 62,
"title": "BEAUTY",
},
{
"id": 325,
"title": "CARE",
对于上述响应,我创建了如下模型:
struct CategoryModel: Codable {
let jsonrpc: String?
let result: ResultCat?
}
struct ResultCat: Codable {
let categories: [Categorymine]?
}
struct Categorymine: Codable {
let id: Int?
let title, slug: String?
}
*APIRestManager中的代码:我在这里进行了通用可编码服务调用,在这里我得到了响应,但在viewcontroller中使用此服务调用时,我没有得到响应,为什么?我哪里错了
import Foundation
import Alamofire
class GeneralResponse<T: Codable>: Codable {
var jsonrpc: String
var result: T?
}
struct RequestObject {
var method: HTTPMethod
var path: String
var token: String?
var params: [String: Any]?
}
class WebService {
private let decoder: JSONDecoder
public init(_ decoder: JSONDecoder = JSONDecoder()) {
self.decoder = decoder
}
public func serviceCall<T: Codable>(_ objectType: T.Type,
with request: RequestObject,
completion: @escaping (T?, Error?) -> Void) {
var headerParams: HTTPHeaders?
AF.request(request.path, method: request.method, parameters: request.params,encoding: JSONEncoding.default, headers: headerParams)
.responseJSON { response in
switch response.result {
case .success(let dictData):
let JSON = dictData as? [String : Any]
do {
let data = response.data
let responseData = try self.decoder.decode(T.self, from: data ?? Data())
print("model data \(String(describing: responseData))")
} catch {
completion(nil, error)
}
case .failure(let error):
let error = error
print(error.localizedDescription)
}
}
}
}
*viewcontroller中的代码:我正在使用下面的服务调用.这里的断点不在WebService()内.serviceCall(CategoryModel.self,with:request){(response,error)在
中,我没有得到响应,为什么?,
note: i need entire CategoryModel
response.
请引导我
class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
var catData: CategoryModel? {
didSet {}
}
override func viewDidLoad() {
super.viewDidLoad()
genericCall()
}
func genericCall(){
let request = RequestObject(method: .get, path: "https://testtt.com/dev/api/get-category", params: nil)
WebService().serviceCall(CategoryModel.self, with: request) { (response, error) in
print("only response in vc \(response)")
if let items = response {
DispatchQueue.main.sync {
self.catData = items
self.tableView.reloadData()
}
}
else{
print(error)
}
}
}
}