【问题标题】:fetch json data to tableview in swift 5在swift 5中将json数据获取到tableview
【发布时间】:2021-01-07 15:33:42
【问题描述】:

我正在尝试在 swift 5 中从 json 中的 php 文件中获取数据到我的 tableview 我能够将控制台中的数据作为 json 数组获取, 我想要的是将数据提取到我的自定义单元格中,但我没有获取 json 数据数组键,例如 data["user_id"] 它没有加载任何内容

my json data one array sample

     func getUsers() {
        
        AF.request(SiteUrl).validate().responseJSON { response in
                switch response.result {
                case .success:
                    print("Validation Successful)")

                    if let json = response.data {
                        do{
                            let data = try JSON(data: json)
                            let str = data
                            print("DATA PARSED: \(str)")
                        }
                        catch{
                        print("JSON Error")
                        }

                    }
                case .failure(let error):
                    print(error)
                }
            }
        
     }
    
     func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return data.count
        
   }

     func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let customCell = tableView.dequeueReusableCell(withIdentifier: TableViewCell.identifier, for: indexPath) as! TableViewCell
       let cell = tableView.dequeueReusableCell(withIdentifier: "myCell", for: indexPath)
       cell.textLabel?.text =  "Hi Hadi"
        
        //customCell.AdTitle.text =

       return customCell
   }
    

【问题讨论】:

  • 我建议你改进你的问题,特别是尽量不要添加图片,看这里=>Why not upload images of code/errors when asking a question?
  • 您似乎没有为您的资源分配任何内容data
  • 这能回答你的问题吗? Returning data from async call in Swift function
  • 解析 JSON 后,您需要重新加载 tableView。另外,避免使用print("JSON Error"),而不是print("JSON Error: \(error)")
  • 不相关,但在 Swift5 中,使用 Codable 代替 SwiftyJSON 可能会更好,并且通常使用 Custom Struct 代替 Dict/array 进行 JSON 解析。

标签: json swift alamofire


【解决方案1】:

首先,强烈建议放弃SwiftyJSON,转而使用Codable

尽管如此,只需创建一个数据源数组,将接收到的数据分配给数据源数组并重新加载表格视图。在cellForRow 中从数组中获取项目并将值分配给相应的 UI 元素

var data = [JSON]()

func getUsers() {
    
    AF.request(SiteUrl).validate().responseJSON { response in
            switch response.result {
            case .success:
                print("Validation Successful)")

                if let json = response.data {
                    do{
                        let jsonData = try JSON(data: json)
                        self.data = jsonData.arrayValue
                        self.tableView.reloadData() // we are already on the main thread
                        print("DATA PARSED: \(jsonData)")
                    }
                    catch {
                        print("JSON Error", error)
                    }
                }
            case .failure(let error):
                print(error)
            }
        }
    
 }

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

 func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
   // let customCell = tableView.dequeueReusableCell(withIdentifier: TableViewCell.identifier, for: indexPath) as! TableViewCell
   let cell = tableView.dequeueReusableCell(withIdentifier: "myCell", for: indexPath)
   let item = data[indexPath.row]
   cell.textLabel?.text = item["user_id"].string
   return cell
}
   

这是现代的方式,首先创建一个结构(你必须根据JSON添加其他成员并使用camelCase名称:"user_id" -> userId

struct User : Decodable {
    let id, contactName : String
    let userId : String
}

并将上面的其他代码替换为

var users = [User]()

func getUsers() {
    let decoder = JSONDecoder()
    decoder.keyDecodingStrategy = .convertFromSnakeCase
    AF.request(SiteUrl).validate().responseDecodable(decoder: decoder) { (response : DataResponse<[User],AFError>) in
        switch response.result {
            case .success(let result): 
                print("Validation Successful)")
                self.users = result
                self.tableView.reloadData()
            case .failure(let error): print("JSON Error", error)
        }    
    }
 }

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

 func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
   // let customCell = tableView.dequeueReusableCell(withIdentifier: TableViewCell.identifier, for: indexPath) as! TableViewCell
   let cell = tableView.dequeueReusableCell(withIdentifier: "myCell", for: indexPath)
   let user = users[indexPath.row]
   cell.textLabel?.text = user.userId
   return cell
}

【讨论】:

  • 感谢@vadian 我收到了这个错误 Cannot assign value of type 'JSON' to type '[JSON]' for self.data = try JSON(data: json) and this error Cannot find 'str'在 print("DATA PARSED: (str)") 的范围内
猜你喜欢
  • 1970-01-01
  • 2020-11-11
  • 1970-01-01
  • 2018-12-10
  • 2021-05-25
  • 2018-07-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多