iOS 13: threading violation: expected the main thread

The app is being crashed when trying to hide the navigation bar for a ViewController only for iOS 13 users.


- I got the crash on Crashlytics of Fabric which titled as below,


Fatal Exception: NSInternalInconsistencyException

threading violation: expected the main thread


- I tried by hiding the NavigationBar for particular ViewController by using NavigationController's delegate method.

func navigationController(_ navigationController: UINavigationController, willShow viewController: UIViewController, animated: Bool) {
  let hide = (viewController is MyVC)
  navigationController.setNavigationBarHidden(hide, animated: animated)
}


Please help.


Thanks

Just put it in the mainQueue:



func navigationController(_ navigationController: UINavigationController, willShow viewController: UIViewController, animated: Bool) {
  let hide = (viewController is MyVC)
  DispatchQueue.main.async { () -> Void in
       self.navigationController.setNavigationBarHidden(hide, animated: animated)
   }
}

If still some problem, maybe you could also use didShoiw instead of willShow

Thanks for the answer,


if I use a mainQueue, then it first being shown the NavigationBar for a second then it is being hidden

So, you have no crash anymore ?


Could you explain (post code) where and how you call the navController that calls the function ?


But I would need to check something:


func navigationController(_ navigationController: UINavigationController, willShow viewController: UIViewController, animated: Bool) { 
  let hide = (viewController is MyVC) 
  DispatchQueue.main.async { () -> Void in 
       self.navigationController.setNavigationBarHidden(hide, animated: animated) 
   } 
}


Line 2, I understand MyVC is a VC that holds the navBar ?

If so, hide is true ?

Hence, line 4, you ask to hide the bar !

So it goes hidden.


Or am I missing somethging ?

iOS 13: threading violation: expected the main thread
 
 
Q