swiftuitableviewswifty-jsonjsonplaceholder

Having trouble appending value from JSON Parsing to array in Swift


I'm playing around with https://jsonplaceholder.typicode.com and I'm trying to create a list of the albums. I tried following the example here, but the list of album titles isn't showing up on the TableView. What am I missing?

class AlbumTableVC: UITableViewController {

var albums = [Album]()

override func viewDidLoad() {
    super.viewDidLoad()
    fetchAlbums()
}

func fetchAlbums() {
    AF.request("https://jsonplaceholder.typicode.com/albums").responseJSON { (response) in
        switch response.result {
        case .success(let value):
            let json = JSON(value)
            
            for value in json.arrayValue {
                let id = value.dictionaryValue["id"]!.int
                let userId = value.dictionaryValue["userId"]!.int
                let title = value.dictionaryValue["title"]!.string
                
                let album = Album(id: id, userId: userId, title: title)
                self.albums.append(album)
            }
        case .failure(let error):
            print(error)
        }
    }
}
// MARK: - Table view data source
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return albums.count
}

override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "AlbumCell", for: indexPath)
    
    let album = albums[indexPath.row]
    cell.textLabel?.text = album.title
    
    return cell
}}

Solution

  • After populating the data source (asynchronously) you have to reload the table view

    for value in json.arrayValue {
        let id = value.dictionaryValue["id"]!.int
        let userId = value.dictionaryValue["userId"]!.int
        let title = value.dictionaryValue["title"]!.string
        
        let album = Album(id: id, userId: userId, title: title)
        self.albums.append(album)
    }
    self.tableView.reloadData()
    

    Consider to drop SwiftyJSON in favor of Codable. Even Alamofire supports it.

    Look at this reduced code, you have just to make Album to adopt Decodable

    struct Album : Decodable { ...
    
    AF.request("https://jsonplaceholder.typicode.com/albums").responseDecodable { (response : DataResponse<[Album],AFError>) in
        switch response.result {
        case .success(let value):
            self.albums = value
            self.tableView.reloadData()
            
        case .failure(let error):
            print(error)
        }
    }