swiftuitableviewuidocument

UIDocument Opening to populate TableView


I am using a DocumentBrowserViewController in Swift to present documents to a ViewController. In the ViewController I have a tableView to present some of the data in the document. When the ViewController is presented, it wants to initialize the tableView first. Settings of the tableView (ex: func TableView: nbrOfRowsInSection) are set by data in the document. Since the document is not read yet it fails.

I have the document.open in the ViewWillAppear which I was thinking would execute first.

Is there a way to change this ordering?


Solution

  • The method viewWillAppear does not execute first, the first one is viewDidLoad. Depending on how you are initialising your ViewController, it can be awakeFromNib as well.

    But it still should not fail, just do something similar to this:

    var dataFromDocument: SomeData {
        didSet {
           tableView.reloadData()
        }
    }
    
    final public func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return dataFromDocument.size
    }
    

    You can then read the data and set dataFromDocument when the reading of the document is finished.