gpt4 book ai didi

ios - 如何重新加载 View Controller 以便 JSON 更新?

转载 作者:行者123 更新时间:2023-11-30 10:53:41 25 4
gpt4 key购买 nike

我正在将一些 JSON 数据加载到 UITableView 中。每个单元格都有一个删除按钮,按下此按钮时,对象将成功从服务器中删除。但是,该页面不会更新以反射(reflect)此更改。我希望重新加载 TableView ,但不删除已删除的对象。我尝试过调用 viewDidLoad() 和 viewDidAppear() 以及我在网上找到的其他几个技巧。目前,我正在使用一种解决方法,将用户发送回主页。从那里,当您单击具有 TableView 的页面时,它已更新以反射(reflect)更改。然而,如果不离开 View Controller 并返回它,我似乎无法实现这一点。我知道 API 调用工作正常,只是页面没有“刷新”。我应该怎样努力才能使这项工作发挥作用?非常感谢!我整个类(class)的代码如下(我添加了一些注释来指出我遇到问题的地方)

import UIKit

class Garage: UIViewController, UITableViewDelegate, UITableViewDataSource {
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return self.vehicles.count
}

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell1", for: indexPath) as UITableViewCell
cell.textLabel?.text = vehicles[indexPath.row].year + " " + vehicles[indexPath.row].make + " " + vehicles[indexPath.row].model
let button = UIButton(type: .custom)
button.backgroundColor = UIColor.green
button.sizeToFit()
cell.accessoryType = .detailButton
return cell
}

func tableView(_ tableView: UITableView, accessoryButtonTappedForRowWith indexPath: IndexPath) {
print("tapped")
let alert = UIAlertController(title: "Would you like to delete this vehicle?", message: "This action cannot be undone.", preferredStyle: .alert)
alert.addAction(UIAlertAction(title: "No", style: .cancel, handler: nil))

self.present(alert, animated: true)
alert.addAction(UIAlertAction(title: "Yes", style: .default, handler: { action in
print("DELETED")
//
//THIS IS WHERE THE DELETE ACTION IS CALLED
//
var id = self.vehicles[indexPath.row].id
print("got here 1")

let api = "https://api.myapi.com/"
let parameters: [String: String] = ["id": id]
guard let url = URL(string: api + id) else { return }
var request = URLRequest(url: url)

let headers: [String: String] = [
"Content-Type": "application/json"
]
request.allHTTPHeaderFields = headers
request.httpMethod = "DELETE"
let requestBody = try? JSONSerialization.data(withJSONObject: parameters, options: [])
if let requestBody = requestBody {
request.httpBody = requestBody
}
//
//THIS IS WHERE I TRY TO RELOAD THE PAGE
//
print("reloading...")
self.viewDidLoad()
self.viewWillAppear(true)
URLSession.shared.dataTask(with: request) { (data, response, error) in
// print("Data, response, error", data, response, error)
if let data = data {
let json = try? JSONSerialization.jsonObject(with: data, options: []) as? [String: Any] ?? [:]
print("json", json)
}
DispatchQueue.main.async {
self.tableVehicles.reloadData()
self.view.setNeedsLayout()
self.performSegue(withIdentifier: "GarageToHome", sender: self)
}

}.resume()
//
//THIS IS MY CURRENT WORK-AROUND
//
self.performSegue(withIdentifier: "GarageToHome", sender: self)
}))
}

@IBOutlet weak var label1: UILabel!

struct Vehicle {
var make: String
var model: String
var year: String
var Trim: String
var id: String
init(_ dictionary: [String: Any]) {
self.make = dictionary["make"] as? String ?? ""
self.model = dictionary["model"] as? String ?? ""
self.year = dictionary["year"] as? String ?? ""
self.Trim = dictionary["trim"] as? String ?? ""
self.id = dictionary["id"] as? String ?? ""
}
}

var vehicles = [Vehicle]()
@IBOutlet weak var tableVehicles: UITableView!

override func viewDidLoad() {
super.viewDidLoad()
// print("login name:", username)
self.tableVehicles.delegate = self
self.tableVehicles.dataSource = self
self.tableVehicles.reloadData()

}

override func viewWillAppear(_ animated: Bool) {
//vehicles = [Vehicle]()
let defaults = UserDefaults.standard
defaults.synchronize()
let token = UserDefaults.standard.string(forKey: "token")
let isSignedIn = UserDefaults.standard.bool(forKey: "isUserLoggedIn")
var username = UserDefaults.standard.string(forKey: "loginName")
defaults.synchronize()
DispatchQueue.main.async {
self.label1.text = "Welcome, " + username! + "!"
defaults.synchronize()
}

guard let url = URL(string: "https://api.myapi.com") else {return}
let task = URLSession.shared.dataTask(with: url) { (data, response, error) in
guard let dataResponse = data,
error == nil else {
print(error?.localizedDescription ?? "Response Error")
return }
do{
let jsonResponse = try JSONSerialization.jsonObject(with:
dataResponse, options: [])
//print(jsonResponse) //Response result
guard let jsonArray = jsonResponse as? [[String: Any]] else {
return
}
for dic in jsonArray{
self.vehicles.append(Vehicle(dic))
}
print(self.vehicles)
DispatchQueue.main.async {
self.tableVehicles.delegate = self
self.tableVehicles.dataSource = self
self.tableVehicles.reloadData()
}
} catch let parsingError {
print("Error", parsingError)
}
}
task.resume()
}
}

最佳答案

首先,永远不要自己调用包含 willdidshould 的委托(delegate)方法。不要那样做。这些方法仅由框架调用。

有一个非常简单的解决方案。您知道已删除行的索引路径,因此如果数据任务成功,则从数据源数组中删除该项目并删除 TableView 中的行。无需重新加载整个 TableView 并根据下载的数据更新数据源数组。

无论如何,您需要一个明确的指示服务器操作是否成功的指标,我不知道 dataTask 中的 if let data = data 是否足够。

//THIS IS WHERE I TRY TO RELOAD THE PAGE
//
print("reloading...")
URLSession.shared.dataTask(with: request) { (data, response, error) in
// print("Data, response, error", data, response, error)
if let data = data {
let json = try? JSONSerialization.jsonObject(with: data) as? [String: Any] ?? [:]
print("json", json)
DispatchQueue.main.async {
self.vehicles.remove(at: indexPath.row)
tableView.deleteRows(at: [indexPath], with: .fade)
self.performSegue(withIdentifier: "GarageToHome", sender: self)
}
}
}.resume()

关于ios - 如何重新加载 View Controller 以便 JSON 更新?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54186682/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com