我如何使用 SwiftyJSON 在 tableview 中填充三个部分

How do i populate three sections in a tableview with SwiftyJSON

我想为 3 个部分 ["Managers","Accountants","Receptionist"] 分配记录或单元格,其中键“authority”验证它属于哪个部分..

Swift代码:

struct GlobalVariables {
        static var userdetailsJSON: [JSON] = [JSON.null]
        static var sectionTitles: [String] = ["Managers","Accountants","Receptionist"]
}
@IBAction func Userdb_Btn(_ sender: Any) {
        let url = "http://.../GetUsers.php"
        let headers: HTTPHeaders = ["Content-Type":"application/x-www-form-urlencoded"]
        let data:  Parameters = ["Authorization":"IOSAPP"]
        AF.request(url, method: .post, parameters: data, encoding: URLEncoding.default, headers: headers).response { response in

            switch response.result {

                       case .success:
                        let json : JSON = JSON(response.data ?? JSON.null)
                        let jsonError = json["error"].boolValue

                        if jsonError ==  false{
                            UsersdbVC.GlobalVariables.userdetailsJSON = json["userDetails"].arrayValue
                            print(UsersdbVC.GlobalVariables.userdetailsJSON)
                        }else{
                            self.displayAlert(title: "Failed to load users data !", message:"")
                        }

                       case .failure(let error):
                        self.displayAlert(title: "Connection error", message: "\(error)")
            }
        }
   }

这是我的 Json 输出:

[{
  "name" : "Oliver",
  "password" : "1234",
  "username" : "Ramy",
  "id" : 84560,
  "authority" : "Manager"
}, {
  "name" : "Maxwell",
  "password" : "1234",
  "username" : "Omar",
  "id" : 84561,
  "authority" : "Accountant"
}, {
  "name" : "Tom",
  "password" : "1234",
  "username" : "Ahmed",
  "id" : 84562,
  "authority" : "Accountant"
}]

节数可以通过以下方式识别:

func numberOfSections(in tableView: UITableView) -> Int {
return GlobalVariables.sectionTitles.count}

但是我们如何通过从关键“权威”验证自身来填充每个部分的记录......? 让我解释一下,我应该在 tableview 中看到如下内容:

Section: Manager
Cell: ID: 84560 - Oliver

Section: Accountant
Cell: ID:84561 - Maxwell
Cell: ID:84562 - Tom

Section: Receptionist
Cell: Empty...

就像按权限过滤或排序... 虽然,以下代码填充了记录,但每个部分都相同...... CellForRowAt:

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "usersTVC", for: indexPath)
        let userID: String = GlobalVariables.userdetailsJSON[indexPath.row]["id"].stringValue
        let userName: String = GlobalVariables.userdetailsJSON[indexPath.row]["name"].stringValue
        cell.textLabel?.text = "ID: \(userID) - \(userName)"
       return cell
   }

节中的行数:

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return GlobalVariables.userdetailsJSON[section]["authority"].count
   }

如有任何帮助,我们将不胜感激!

忘记 SwiftyJSON,它是一个很棒的库,但它已经过时了。
并且忘记一个具有静态属性的结构作为数据源。

使用 Decodable 解码 JSON – AlamoFire 确实支持它 – 并将使用 Dictionary(grouping:by:) 的数组分组。


首先创建两个结构,一个用于节,一个用于项目(下例中的User

struct Section {
    let name : String
    let users : [User]
}

struct User : Decodable {
    let name, password, username, authority : String
    let id : Int
}

这是一个没有AF的独立解决方案,创建一个数据源数组

var sections = [Section]()

解码JSON

let jsonString = """
[{
  "name" : "Oliver",
  "password" : "1234",
  "username" : "Ramy",
  "id" : 84560,
  "authority" : "Manager"
}, {
  "name" : "Maxwell",
  "password" : "1234",
  "username" : "Omar",
  "id" : 84561,
  "authority" : "Accountant"
}, {
  "name" : "Tom",
  "password" : "1234",
  "username" : "Ahmed",
  "id" : 84562,
  "authority" : "Accountant"
}]
"""

do {
    let users = try JSONDecoder().decode([User].self, from: Data(jsonString.utf8))
    let grouped = Dictionary(grouping: users, by: \.authority)
    sections = grouped.map(Section.init)
    
    print(sections)
} catch {
    print(error)
}

数据源方法是

func numberOfSections(in tableView: UITableView) -> Int {
    return sections.count
}

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return sections[section].users.count
}

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "usersTVC", for: indexPath)
    let user = sections[indexPath.section].users[indexPath.row]
    cell.textLabel?.text = "ID: \(user.id) - \(user.name)"
    return cell
}

更新:要使用 Alamofire 解码 JSON,请使用

AF.request(url, method: .post, parameters: data, headers: headers).responseDecodable(of: [User].self, decoder: JSONDecoder()) { response in
    switch response.result {
        case .success(let users): 
           let grouped = Dictionary(grouping: users, by: \.authority)
           sections = grouped.map(Section.init)
        case .failure(let error): print(error)