MBProgressHUD Block interface until operation is done

Viewed 4995

I need to block the interface until the MBProgressHUD operation is done. I did refer this thread,

Block interface until operation is done

According to it, we should disable each individual item which wont work for me. My case is I need to disable user from clicking back button. I did try HUD.userInteractionEnabled = YES which disable every controller except the back button. Is there any way of blocking user from popping out from that controller?

Regards,
Dilshan

5 Answers

@sujith1406's answer is correct. However, the methods he mentioned are deprecated from iOS 13. Here is my protocol based solution to implement MBProgressHUD blocking.

import Foundation
import MBProgressHUD

protocol AppLoader {
    func showLoader()
    func hideLoader()
}

extension AppLoader where Self: UIViewController {
    func showLoader() {
        let views: [UIView?] = [self.navigationController?.view, view]
        views.forEach({ $0?.isUserInteractionEnabled = false })
        MBProgressHUD.showAdded(to: self.view, animated: true)
    }
    
    func hideLoader() {
        let views: [UIView?] = [self.navigationController?.view, view]
        views.forEach({ $0?.isUserInteractionEnabled = true })
        MBProgressHUD.hide(for: self.view, animated: true)
    }
}

extension UIViewController: AppLoader {}

how to use it?

func fetchUserInformation() {
   self.showLoader()
   //perform api call. assuming fetchUserData is an api that fetches a particular user data from the server.
   self.fetchUserData(completion: { [weak self] in 
       self?.hideLoader()
   })
}
Related