Riempire una UITable da JSON in Swift

Mattepuffo's logo
Riempire una UITable da JSON in Swift

Riempire una UITable da JSON in Swift

Personalmente trovo Swift ancora complicato rispetto ad altri linguaggi; quindi cercherò di essere più chiaro possibile per chi ha le mie stesse difficoltà.

Cominciamo con il dire che i dati li prenderemo da un service remoto e sono in formnato JSON.

Se volete prima studiarvi la struttura del JSON andate a questo indirizzo: https://www.mattepuffo.com/api/book/all.php.

Come vedete abbiamo un array di oggetti; noi prenderemo solo title e author.

Questo sarà il vostro ViewController:

import UIKit

struct Book {
    let title: String
    let author: String
    
    public init(title: String, author: String) {
        self.title = title
        self.author = author
    }
}

class ViewController: UITableViewController  {
    
    var tableArray = [Book] ()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        self.tableView.dataSource = self
        self.tableView.delegate = self
        
        getJson()
    }
    
    func getJson() {
        
        let url = URL(string: "https://www.mattepuffo.com/api/book/all.php")
        
        let task = URLSession.shared.dataTask(with: url!) {(data, response, error) in
            
            guard let jsonData = url else {
                return
            }
            
            guard let data = try? Data(contentsOf: jsonData) else { return }
            
            guard let json = try? JSONSerialization.jsonObject(with: data, options: []) else{ return }
            
            if let dictionary = json as? [String: Any] {
                
                guard let jsonArray = dictionary["books"] as? [[String: Any]] else {
                    return
                }
                
                for j in jsonArray {
                    guard let title = j["title"] as? String else { return }
                    guard let author = j["author"] as? String else { return }
                    self.tableArray.append(Book(title: title, author: author))
                }
                
            }
            
            DispatchQueue.main.async {
                self.tableView.reloadData()
            }
            
        }
        
        task.resume()
        
    }
    
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
    }
    
}

extension ViewController {
    
    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return self.tableArray.count
    }
    
    override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        print(self.tableArray[indexPath.row])
        tableView.deselectRow(at: indexPath, animated: true)
    }
    
    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let current = self.tableArray[indexPath.row]
        let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath) as UITableViewCell
        cell.textLabel?.text = current.title
        cell.detailTextLabel?.text = "(current.author)"
        return cell
    }
    
}

Abbiamo un struct che corrispdonde alla struttura dei dati che vogliamo visualizzare.

Il tutto viene fatto in maniera asincrona dalla funzione getJson().

In fondo abbiamo una estensione del ViewController in cui facciamo l'override di alcune funzioni.

Adesso viene la parte più difficile da spiegare, perchè dobbiamo sistemare la storyboard.

Prima di tutto cancellate tutto il contenuto e aggiungete un oggetto UITableViewController.

Poi in View Controller Scene dovete impostare la classe ViewController nell'Identity ispector; e dovete impostarlo come Is Initial View Controller nell'Attribute inspector.

In Cell, nell'Attribute inspector, impostate Subtitle.

In Content View aggiungete due UILabel e chiamate Title e Author.

 

Non dovrei essermi dimenticato nulla; può essere che alcune voci dei menu cambino a seconda della versione di XCode.

Ma ci sta tutto, basta spulicare tra le voci.

Enjoy!


Condividi

Commentami!