-1

I am creating a custom button for navigation back action. And on back-button click, pushing a different view controller which is not pushed. The back action working fine but the showing loader is not consistent. What is the best practice for such a case?

Code for back-action as follow:

@objc func backAction() -> Void {
    self.showLoader { (status) in
        if status {
            DispatchQueue.main.async {                    
                if let viewController = UIStoryboard(name: DFViewControllerNameConstant.MAIN, bundle: nil).instantiateViewController(withIdentifier: DFViewControllerNameConstant.DF_PREVIEW_ALL_TOUR_VIEW_CONTROLLER) as? DFPreviewAllPublishedCapturePanoramaViewController {
                    if let navigator = self.navigationController {
                        navigator.pushViewController(viewController, animated: true)
                    }
                }
            }
        }
    }
}

And code for Show and remove loader is:

import UIKit
fileprivate var loaderView: UIView?

extension UIViewController {
    func showLoader(completion: @escaping ((Bool)->())) {
        loaderView = UIView(frame: self.view.bounds)
        loaderView?.backgroundColor = UIColor.init(red: 0.4, green: 0.4, blue: 0.4, alpha: 0.4)
        let loader = UIActivityIndicatorView(style: .white)
        loader.center = loaderView!.center
        loader.startAnimating()
        loaderView?.addSubview(loader)
        self.view.addSubview(loaderView!)
        UIApplication.shared.beginIgnoringInteractionEvents()
        completion(true)
    }

    func removeLoader() {
        loaderView?.removeFromSuperview()
        loaderView = nil
        UIApplication.shared.endIgnoringInteractionEvents()
    }
}
Naresh Pawar
  • 179
  • 2
  • 3
  • 15

2 Answers2

0

If you want to show the loader consistently you should add your Activity IndicatorView to your apps window and not to the particular viewcontroller's view.

Something like this - (UIApplication.shared.delegate as! AppDelegate).window?.addSubview(<#T##view: UIView##UIView#>)

Help
  • 84
  • 4
0

Issue resolved changing backAction() by following way:

    @objc func backAction() -> Void {
        DispatchQueue.main.async {
            self.showLoader()
            DispatchQueue.main.async {
                if let viewController = UIStoryboard(name: DFViewControllerNameConstant.MAIN, bundle: nil).instantiateViewController(withIdentifier: DFViewControllerNameConstant.DF_PREVIEW_ALL_TOUR_VIEW_CONTROLLER) as? DFPreviewAllPublishedCapturePanoramaViewController {
                    DispatchQueue.main.async {
                        if let navigator = self.navigationController {
                            navigator.pushViewController(viewController, animated: true)
                        }
                    }
                }
            }
        }
    }
Naresh Pawar
  • 179
  • 2
  • 3
  • 15