Show SVProgressHUD on viewWillDisappear

102 Views Asked by At

Context : My UIViewController is showing an edit profile view, with a few UITextField (first name, last name, birthday, ...). There is no "save button", the values update on the database as soon as the textFieldDidEndEditing is called.

I want to show a loading view (I'm using SVProgressHUD library) if the user try to leave the UIViewController before all database updates are finished.

So here is my code (if updateWaitingConfirm is empty that means all updates are done) :

override func viewWillDisappear(_ animated: Bool) {
    
    if !updateWaitingConfirm.isEmpty {
        
        self.showSVProgressHUD(message: NSLocalizedString("updateWaiting", comment: ""))
        
        timeToWaitCount = 0
        let group = DispatchGroup()
        group.enter()
        
        checkWaitingConfirmEmpty(group)
        
        group.wait()
        self.dismissSVProgressHUD()
    }
    
    super.viewWillDisappear(animated)
}

func checkWaitingConfirmEmpty(_ group: DispatchGroup) {
    
    DispatchQueue.global(qos: .default).asyncAfter(deadline: .now() + 0.5) {
        self.timeToWaitCount += 0.5
        if self.updateWaitingConfirm.isEmpty || self.timeToWaitCount > self.maxTimeToWaitForUpdates {
            group.leave()
        } else {
            self.checkWaitingConfirmEmpty(group)
        }
    }
}

When all updates are done (or when it's been more than maxTimeToWaitForUpdates (10 seconds)), the group.leave() is called and then I call my function to dismissHUD and call the super.viewWillDisappear()

The problem is that nothing appears on my view, I also tried to edit a textfield for example and it doesn't work either. I also tried to call view.layoutIfNeeded() after the showSVProgressHUD but it's not working.

Good to know : I can't just call a method on my back button touchUpInside method because the user can also quit the UIViewController with interactivePopGestureRecognizer.

Thanks!

0

There are 0 best solutions below