首页 > 解决方案 > iOS 12.2:CMMotionManager 阻塞了主线程

问题描述

CoreMotion对以下代码有疑问:

let motionManager = CMMotionManager()

它阻塞了我的主线程 4-5 秒,我不知道为什么。当我将 iPhone XR 更新到 12.2 时出现问题。它不会在 12.1.3 上使用 iPhone 6S 阻塞主线程。

我认为这可能是硬件问题或iOS版本。

谢谢

标签: iosswiftcore-motionios12cmmotionmanager

解决方案


CoreMotion 在初始化期间自己做了很多事情。
移动初始化做一个不同的线程。
编辑:

我可以在开发 iPhone Xs 上确认 12.2 的问题。在真实使用的设备上没有问题。我还看到了违反警告,告诉 CoreMotion 尝试从后台线程访问 Applicationstate。

但是,将 init 移动到单独的线程可以修复任何 UI 挂起。coremotion 的初始化仍然需要一段时间。我创建了一个空的单视图应用程序项目并更改了 ViewController 类

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
    }

}

没有单独的线程,红色仍然存在。使用单独的线程,颜色在 dev XS 上是瞬间黄色,最后是绿色,在我的 iPhone 8Plus 上是瞬间绿色。

补充:
有趣的是,没有附加 XCode,开发设备没有问题。尝试在不连接到调试器的情况下运行您的代码。


推荐阅读