Search code examples
iosswiftxcodeviewwillappear

How to stop viewWillAppear from completing until a function has finished


I'm pretty new to IOS Application Development.

I'm trying to stop viewWillAppear from finishing until after my function has finished working. How do I do that?

Here's viewWillAppear:

override func viewWillAppear(animated: Bool) {
    super.viewWillAppear(true)

    checkFacts()

    if reset != 0 {
        print("removing all bird facts")
        birdFacts.removeAll()
    }
}

func checkFacts() {
    let date = getDate()
    var x: Bool = true
    var ind: Int = 0
    print("count is ", birdFacts.count)
    while ind < birdFacts.count {
        print("accessing each bird fact in checkFacts")
        let imageAsset: CKAsset = birdFacts[ind].valueForKey("birdPicture") as! CKAsset
        let image = UIImage(contentsOfFile: imageAsset.fileURL.path!)
        print(image)
        if image == nil {
            if (birdFacts[ind].valueForKey("sortingDate") != nil){
                print("replacing fact")
                print("accessing the sortingDate of current fact in checkFacts")
                let sdate = birdFacts[ind].valueForKey("sortingDate") as! NSNumber
                replaceFact(sdate, index: ind)
            }
            /*else {
                birdFacts.removeAll()
                print("removing all bird facts")
            }*/

        }
        ind = ind + 1
        print(ind)
    }
    self.saveFacts()
    let y = checkRepeatingFacts()
    if y {
        print("removing all facts")
        birdFacts.removeAll()
        //allprevFacts(date, olddate: 0)
    }
}

checkFacts references 2 others functions, but I'm not sure they're relevant here (but I will add them in if they are and I'm mistaken)


Solution

  • So based on the comments, checkFacts is calling asynchronous iCloud operations that if they are not complete will result in null data that your view cannot manage.

    Holding up viewWillAppear is not the way to manage this - that will just result in a user interface delay that will irritate your users.

    Firstly, your view should be able to manage null data without crashing. Even when you solve this problem there may be other occasions when the data becomes bad and users hate crashes. So I recommend you fix that.

    To fix the original problem: allow the view to load with unchecked data. Then trigger the checkData process and when it completes post an NSNotification. Make your view watch for that notification and redraw its contents when it occurs. Optionally, if you don't want your users to interact with unchecked data: disable appropriate controls and display an activity indicator until the notification occurs.