1

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
   }
    
5
  • I suggest you improve your question,especially try to don’t add a picture, Have a look here => Why not upload images of code/errors when asking a question? Commented Jan 7, 2021 at 16:12
  • It doesn't look like you assign anything to your property data Commented Jan 7, 2021 at 16:34
  • 1
    Does this answer your question? Returning data from async call in Swift function Commented Jan 7, 2021 at 16:34
  • You need to reload your tableView once your parsed your JSON. Also, avoid using print("JSON Error"), instead print("JSON Error: \(error)"). Commented Jan 7, 2021 at 16:36
  • 1
    Not related, but in Swift5, it might be better to use Codable instead of SwiftyJSON, and in general to use Custom Struct instead of Dict/array for JSON parsing. Commented Jan 7, 2021 at 16:37

1 Answer 1

1

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
}
Sign up to request clarification or add additional context in comments.

1 Comment

thanks @vadian I got this errors Cannot assign value of type 'JSON' to type '[JSON]' for self.data = try JSON(data: json) and this error Cannot find 'str' in scope for print("DATA PARSED: (str)")

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.