Search code examples
iosswiftuiviewcontrolleruibuttonviewwillappear

how to prevent button showing up for split second when view loads


So my goal is to smoothly load the viewController with no split second bugs. I have a function that is used to determine what buttons to show when the view loads based off a field in a Firestore document. Here is the function:

func determinePurchasedStatusVerification() {
    db.collection("student_users/\(user?.uid)/events_bought").whereField("event_name", isEqualTo: selectedEventName!).whereField("isEventPurchased", isEqualTo: true).getDocuments { (querySnapshot, error) in
        if let error = error {
            print("\(error)")
        } else {
            guard let querySnap = querySnapshot?.isEmpty else { return }
            if querySnap == true {
                self.purchaseTicketButton.isHidden = false
                self.viewPurchaseButton.isHidden = true
                self.cancelPurchaseButton.isHidden = true
            } else {
                self.purchaseTicketButton.isHidden = true
                self.viewPurchaseButton.isHidden = false
                self.cancelPurchaseButton.isHidden = false
            }
        }
    }

}

I call this function in the viewWillAppear() of the vc but when I instantiate to that vc, this is the result...

vc error

The extra purchase ticket button shows up for a split second. Even though it's very quick, you can still see it and it's just not something a user would need to see. It's also the other way around when you click on a cell that's not purchased, the two bottom buttons show up for a split second. I just want to know how I can prevent this quick bug and be able to display a smooth segue with no delays in the button hiding. Thanks.


Solution

  • getDocuments is an asynchronous function, meaning it doesn't call its callback function immediately -- it calls it when it gets data back from the server. It may seem like a split second just because your internet connection is fast and the Firebase servers are definitely fast, but it's a non-zero time for sure. And, someone with a slower connection might experience much more of a delay.

    Unless your callback is getting called twice with different results (which seems doubtful), the only solution here is to make sure that your initial state has all of the buttons hidden (and maybe a loading indicator) and then show the buttons that you want once you get the data back (as you are right now). My guess is, though, that you have an initial state where the buttons are visible, which causes the flicker.