Creare una loading dialog in Swift e iOS

Mattepuffo's logo
Creare una loading dialog in Swift e iOS

Creare una loading dialog in Swift e iOS

In questo articolo abbiamo visto come riempire una UITableViewController da un JSON remoto usando Swift.

Qui aggiungiamo un pezzo, e ciè un loading dialog.

In pratica una "finestra" in overlay che ci visualizza il classico loading.

Vi posto tutto il codice del controller, indicando quelle che sono le aggiunte da fare:

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] ()

    // LA VIEW CHE FA DA DIALOG
    var loadingView : UIView?
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        self.tableView.dataSource = self
        self.tableView.delegate = self
        
        getJson()
    }
    
    func getJson() {
        // AVVIAMO IL DIALOG PRIMA DELLA RICHIESTA
        self.showSpinner(onView: self.view)
        
        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()
                // RIMUVIAMO IL DIALOG ALLA FINE DELLA RICHIESTA
                self.removeSpinner()
            }
            
        }
        
        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
    }
    
    // FUNZIONE CHE AVVIA IL DIALOG
    func showSpinner(onView : UIView) {
        let spinnerView = UIView.init(frame: onView.bounds)
        spinnerView.backgroundColor = UIColor.init(red: 0.5, green: 0.5, blue: 0.5, alpha: 0.5)
        let ai = UIActivityIndicatorView.init(style: .whiteLarge)
        ai.startAnimating()
        ai.center = spinnerView.center
        
        DispatchQueue.main.async {
            spinnerView.addSubview(ai)
            onView.addSubview(spinnerView)
        }
        
        loadingView = spinnerView
    }
    
    // FUNZIONE CHE RIMUOVE IL DIALOG
    func removeSpinner() {
        DispatchQueue.main.async {
            self.loadingView?.removeFromSuperview()
            self.loadingView = nil
        }
    }
}

Ovviamente possiamo apportare dei miglioramenti.

Come ad esempio renderlo riutilizzabile da altri controller.

Enjoy!


Condividi

Commentami!