ios - 修改 UITableView 中的 JSON 数组

标签 ios swift uitableview

我似乎无法理解在 UITableView 中呈现 JSON 数组时如何编辑?

The JSON array looks like the following example:

[
    {
        "customer": "John",
        "status": "Yes",
    },
    {
        "customer": "James",
        "status": "No",
    },
    {
        "customer": "Jamie",
        "status": "No",
    }
]

应用当前在 UITableView 中呈现数据的方式:

private func fetchJSON() {

    guard let url = URL(string: "https://example/example/example"),
        let value = driver.addingPercentEncoding(withAllowedCharacters: .urlQueryValueAllowed)
        else { return }

    var request = URLRequest(url: url)
    request.httpMethod = "POST"
    request.httpBody = "driver=\(value)".data(using: .utf8)

    URLSession.shared.dataTask(with: request) { data, _, error in
        guard let data = data else { return }

        do {
            self.structure = try JSONDecoder().decode([Structure].self,from:data)
            DispatchQueue.main.async {
                self.tableView.reloadData()

            }
        }
        catch {
            print(error)
        }
        }.resume()

} 

到目前为止的 TableView 委托(delegate)代码:

override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    if isFiltering() {
        return pickup.count
    }
    print(structure.count)
    return structure.count
}

override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {


    let cell = tableView.dequeueReusableCell(withIdentifier: "testingCell", for: indexPath)


    let portfolio: Structure

    portfolio = structure[indexPath.row]

    return cell

}

override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {

    tableView.cellForRow(at: indexPath)?.accessoryType = .checkmark

}

override func tableView(_ tableView: UITableView, didDeselectRowAt indexPath: IndexPath) {
    tableView.cellForRow(at: indexPath)?.accessoryType = .none

}

我希望能够选择客户姓名 James 和 Jamie,然后按下按钮将状态从“否”更改为"is"。

如何从应用程序的角度创建选择和更新机制?

更新:

结构体定义为:var Structure = [Structure]()

import UIKit

struct Structure: Codable {
    let customer: String
    let status: String
}

更新 2:

我正在使用以下内容,但我似乎无法更新 API:

func saveToDB(_ structure: Structure) {
    do{
        let data = try JSONEncoder().encode(structure)
        if let str = String(data: data, encoding: .utf8) {
            print(str)

                guard let url = URL(string: "https://example/example/example"),
        else { return }
        }
    } catch {
        print(error)
    }
}

最佳答案

您必须更改 statusstructure array w.r.t 所选 indexPath而不是直接在 JSON 中。

tableView(_: didSelectRowAt:)tableView(_: didDeselectRowAt:) ,您只需更改 status structure 的值在那个特定的indexPath像这样,

override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    structure[indexPath.row].status = "Yes"
    tableView.cellForRow(at: indexPath)?.accessoryType = .checkmark
}

override func tableView(_ tableView: UITableView, didDeselectRowAt indexPath: IndexPath) {
    structure[indexPath.row].status = "No"
    tableView.cellForRow(at: indexPath)?.accessoryType = .none
}

如果问题没有解决,请添加 Structure 的定义以及更多详细信息,以便我可以为您提供进一步帮助。

编辑:

首先,Structure的定义就像,

class Structure: Codable {
    var customer: String
    var status: String
}

更新status的代码的structure一个indexPath是:

class VC: UIViewController, UITableViewDataSource, UITableViewDelegate {
    @IBOutlet weak var tableView: UITableView!
    var structures = [Structure]()

    override func viewDidLoad() {
        super.viewDidLoad()
        tableView.allowsMultipleSelection = true
        fetchJSON()
    }

    private func fetchJSON() {
        //code to fetch data from JSON...
    }

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return structures.count
    }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "testingCell", for: indexPath)
        cell.textLabel?.text = structures[indexPath.row].customer
        return cell
    }

    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        let structure = structures[indexPath.row]
        structure.status = "Yes"
        saveToDB(structure)
        tableView.cellForRow(at: indexPath)?.accessoryType = .checkmark
    }

    func tableView(_ tableView: UITableView, didDeselectRowAt indexPath: IndexPath) {
        let structure = structures[indexPath.row]
        structure.status = "No"
        saveToDB(structure)
        tableView.cellForRow(at: indexPath)?.accessoryType = .none
    }

    func saveToDB(_ structure: Structure) {
        //add the code to save structure in DB...
    }
}

现在,当保存到数据库时,不需要JSON 响应。您可以直接保存structure 数据库中的实例。

编辑2:

更新 saveToDB(_:)方法:

func saveToDB(_ structure: Structure) {
    do{
        let data = try JSONEncoder().encode(structure)
        if let str = String(data: data, encoding: .utf8) {
            print(str)
            //str is the updated Structure that you can send in your API...
        }
    } catch {
        print(error)
    }
}

在上述方法中,您将获得更新后的 structureJSON 格式您可以用来调用 API 的实例。

关于ios - 修改 UITableView 中的 JSON 数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57405620/

相关文章:

ios - Alamofire 不执行该 URL

ios - 有没有办法可以更改消息套件中整个输入栏的背景颜色?

swift - 使用 datePicker 更改 cell.textField.text

ios - FireMonkey,IOS FMX.Listview

java - java在 objective-c 中的并发hashmap的等价物

ios - 无法将类型 'NSTaggedPointerString' 的值转换为 'NSDictionary'。 swift/火力基地

ios - 由一对多关系创建的访问器方法是否与 NSFetchedResultsControllers 一样好?

ios - 如何使用 IBAFormSection 减小宽度?

ios - 为什么崩溃会随着 "zombie objects"消失?

iphone - EXC_BREAKPOINT 崩溃。可能越狱问题?