iOS 12.2 : CMMotionManager is blocking the main thread

783 Views Asked by At

I have an issue with CoreMotion and the following code :

let motionManager = CMMotionManager()

It blocks my Mainthread for 4-5 seconds and I don't know why. The problem appears when I updated my iPhone XR to 12.2. It does not block the mainthread with a iPhone 6S on 12.1.3.

I think it may be a hardware problem or iOS version.

Thank you

1

There are 1 best solutions below

3
Helge Becker On BEST ANSWER

CoreMotion is doing a lot on his own during init.
Move the initialisation do a different thread.
Edit:

I can confirm the issue with 12.2 on a development iPhone Xs. No issue on a real used device. I see also violation warnings telling CoreMotion tries to access the Applicationstate from a background thread.

However moving the init to a separate thread fixes any UI hangs here. The init of coremotion still does take a while. I created a empty single view application project and changed the ViewController class

class ViewController: UIViewController {

    var motionManager: CMMotionManager?

    override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated)
        view.backgroundColor = UIColor.red
        DispatchQueue.global().async {
            self.motionManager = CMMotionManager()
            DispatchQueue.main.async {
                self.view.backgroundColor = UIColor.green
            }
        }
        view.backgroundColor = UIColor.yellow
    }

}

Without a separate thread, the red color remains. With a separate thread the color is instant yellow and finally green on the dev XS and instant green on my iPhone 8Plus.

Addition:
Interestingly, without XCode attached, the dev device has no issues. Try to run your code without being connected to the Debugger.