Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
812 views
in Technique[技术] by (71.8m points)

fetch json data to tableview in swift 5

I am trying to fetch data from php file in json to my tableview in swift 5 I am able to get the data in the console as json array, what I want is to fetch the data into my custom cell but I am not getting the json data array keys for example data["user_id"] it is not loading anything

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
   }
    

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

First of all it's highly recommended to drop SwiftyJSON in favor of Codable.

Nevertheless just create a data source array, assign the received data to the data source array and reload the table view. In cellForRow get the item from the array and assign the values to the corresponding UI elements

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
}
   

And this is the modern way, first create a struct (you have to add the other members according to the JSON and use camelCase names: "user_id" -> userId)

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

and replace the other code above with

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
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...