我用Json中的请求数据制作了API文件,还制作了一个不同的类型数据结构,但我在检索数据时遇到了问题,它显示的是空的tableView,而不是至少显示我制作的单元格。
这是tableView:的返回代码
extension MonitorimiViewController: UITableViewDelegate, UITableViewDataSource {
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return vehicles.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "monitorimiCell", for: indexPath) as! MyCustomCell1
cell.configure()
return cell
}
这是包含必须填写在Cell标签中的数据的结构文件:
struct Vehicles: Codable {
var Plate: String?
var Speed: Int
var LastCommunicationDate: Int
var Passengers: Int
var Driver: String
}
这是API请求文件:
class APICaller {
static let shared = APICaller()
private let baseURL = "http://000.000.000.000:3030/api/"
private init() {}
func getVehicles(for id: String, IMEI: Int, completed: @escaping (Result<[Vehicles],OnTraErrors>) -> Void ){
let endpoint = baseURL + "GetVehicle/?UserIdentificationValue=JJGI243GJI3G&IMEI=623624346236"
let headers = [
"content-type": "application/json",
"authorizetoken": "NjQzOPA2N0NDNDFAH4CNDk3R23F2FQUY0NjV3FFE=",
"cache-control": "no-cache",
]
guard let url = URL(string: endpoint) else {
completed(.failure(.invalidURL))
return
}
var request = URLRequest(url: url, cachePolicy: .useProtocolCachePolicy, timeoutInterval: 120)
request.httpMethod = "POST"
request.allHTTPHeaderFields = headers
let session = URLSession.shared
let task = session.dataTask(with: request) { data, response, error in
if let _ = error {
completed(.failure(.unableToComplete))
return
}
guard let response = response as? HTTPURLResponse, response.statusCode == 200 else {
completed(.failure(.invalidResponse))
return
}
guard let data = data else {
completed(.failure(.invalidData))
return
}
do {
let decoder = JSONDecoder()
decoder.keyDecodingStrategy = .convertFromSnakeCase
let vehicles = try decoder.decode([Vehicles].self, from: data)
completed(.success(vehicles))
} catch {
completed(.failure(.invalidData))
}
}
task.resume()
}
因此,当我将返回车辆更改为返回10时,它只显示我的单元格如下:[1]:https://i.stack.imgur.com/aVp5Z.png
但现在它向我展示了这一点,而不是填充这些标签[2]:https://i.stack.imgur.com/RG4bb.png
确保您正在重新加载UITableView
,您只需观察dataSource变量
var vehicles: [Vehicles] = [] { // i suggest renaming Vehicles struct to vehicle
didSet {
tableView.reloadDate()
}
}