基本上,一旦发出POST请求并且API用JSON响应,我就需要在表视图中显示JSON数据。
我没有收到任何错误,但也没有收到调试器中显示的任何JSON响应。我不知道到底是什么问题,但似乎没有任何东西加载或显示在tableview中。
以下是我用来解释JSON的结构:
import UIKit
struct ScheduleStructure: Codable {
let customer: String
let PickedUpNUM: String
let DeliveryNUM: String
}
这是JSON的样子:
[
{
"customer": “Example”,
"PickedUpNUM": “2”,
"DeliveryNUM": “4”
}
]
这是当前的tableview控制器:
import UIKit
class ScheduleCell: UITableViewCell {
@IBOutlet weak var cellStructure: UIView!
@IBOutlet weak var testingCell: UILabel!
@IBOutlet weak var pickupLabel: UILabel!
@IBOutlet weak var deliveryLabel: UILabel!
}
class ScheduleTableViewController: UITableViewController {
var driverName = UserDefaults.standard.string(forKey: "name")!
var structure = [ScheduleStructure]()
override func viewDidLoad() {
super.viewDidLoad()
UINavigationBar.appearance().isTranslucent = false
self.view.backgroundColor = UIColor.white
//Adds Shadow below navigation bar
self.navigationController?.navigationBar.layer.masksToBounds = false
self.navigationController?.navigationBar.layer.shadowColor = UIColor.lightGray.cgColor
self.navigationController?.navigationBar.layer.shadowOpacity = 0.8
self.navigationController?.navigationBar.layer.shadowOffset = CGSize(width: 0, height: 2.0)
self.navigationController?.navigationBar.layer.shadowRadius = 2
self.extendedLayoutIncludesOpaqueBars = true
fetchJSON()
let refreshControl = UIRefreshControl()
refreshControl.addTarget(self, action: #selector(doSomething), for: .valueChanged)
tableView.refreshControl = refreshControl
}
private func fetchJSON() {
guard
let url = URL(string: "https://example.com/example/example.php"),
let value = driverName.addingPercentEncoding(withAllowedCharacters: .urlQueryValueAllowed)
else { return }
var request = URLRequest(url: url)
request.httpMethod = "POST"
request.httpBody = "value=\(value)".data(using: .utf8)
URLSession.shared.dataTask(with: request) { data, _, error in
DispatchQueue.main.async {
//
}
}.resume()
}
@objc func doSomething(refreshControl: UIRefreshControl) {
print("reloaded")
fetchJSON()
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return structure.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "customerID", for: indexPath) as! ScheduleCell
cell.textLabel?.font = .boldSystemFont(ofSize: 18)
cell.textLabel?.textColor = UIColor.red
let portfolio = structure[indexPath.row]
cell.textLabel?.text = portfolio.customer
return cell
}
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let cell = tableView.dequeueReusableCell(withIdentifier: "customerID", for: indexPath) as! ScheduleCell
//cell.cellStructure.layer.cornerRadius = 50
let portfolio = structure[indexPath.row]
let navigationController = UINavigationController(rootViewController: controller)
self.present(navigationController, animated: true, completion: nil)
}
override func viewWillAppear(_ animated: Bool) {
fetchJSON()
}
}
请告诉我是否有一种更好的方法
我只需要执行JSON POST并将结果显示在表中即可。
答案 0 :(得分:0)
您需要将json响应解码为api回调内的数组
URLSession.shared.dataTask(with: request) { data, _, error in
guard let data = data else { return }
do {
self.structure = try JSONDecoder().decode([ScheduleStructure].self,from:data)
DispatchQueue.main.async {
self.tableView.reloadData()
}
}
catch {
print(error)
}
}.resume()
struct ScheduleStructure: Codable {
let customer, pickedUpNUM, deliveryNUM: String
enum CodingKeys: String, CodingKey {
case customer
case pickedUpNUM = "PickedUpNUM"
case deliveryNUM = "DeliveryNUM"
}
}
答案 1 :(得分:0)
我假设您知道dataTask
的主体实际上并未对其接收的数据做任何事情?那里只有一个空的评论。
我猜你想做这样的事情:
if let data = data {
do {
self.structure = try JSONDecoder().decode(Array<ScheduleStructure>.self, from: data)
self.reloadData()
} catch {
print("TODO: handle parse error: \(error)")
}
} else {
print("TODO: handle network error: \(error)")
}