xcode - 运动管理器不工作

标签 xcode swift swift2 ios9 cmmotionmanager

我正在尝试获取设备运动(俯仰、滚动、偏航),但我的函数 handleDeviceMotionUpdate 未启动(我正在 iphone 5s 上尝试),这是代码:

import UIKit
import CoreMotion

class ViewController: UIViewController {

override func viewDidLoad() {
    super.viewDidLoad()






    var motionManager = CMMotionManager()
    motionManager.startDeviceMotionUpdates()
    motionManager.deviceMotionUpdateInterval = 0.1


    motionManager.startDeviceMotionUpdatesToQueue(
        NSOperationQueue.currentQueue()!, withHandler: {
            (deviceMotion, error) -> Void in

            if(error == nil) {
                self.DeviceMotionUpdate(deviceMotion!)
            } else {
                print("error")
            }
    })

}


override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()

}

func DeviceMotionUpdate(deviceMotion:CMDeviceMotion) {
    print("function launched")
    var attitude = deviceMotion.attitude
    var roll = (attitude.roll)
    var pitch = (attitude.pitch)
    var yaw = (attitude.yaw)
    print("Roll: \(roll), Pitch: \(pitch), Yaw:  (yaw)")

}



}

我没有在 startDeviceMotionUpdatesToQueue 中收到错误。我在 motionManager.deviceMotionActive 和 motionManager.deviceMotionAvailable 上得到 true

最佳答案

您的 motionManager 可能在运行完 viewDidLoad 方法后被销毁。尝试使 motionManager 成为类属性。

class ViewController: UIViewController {
    var motionManager = CMMotionManager()

    override func viewDidLoad() {
        super.viewDidLoad()

        self.motionManager.startDeviceMotionUpdates()

        ...

关于xcode - 运动管理器不工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37908854/

相关文章:

ios - 如何使用 swift 登录带有 javascript 的网站?

ios - 可以刷新整个核心数据对象吗?

iphone - 获取时间间隔并在 Objective-C 中播放声音

ios - 在视频启动时在 UIWebView 中调整 YouTube 视频缩略图

ios - Swift 3 类型 'Any?' 的值没有成员 'object'

ios - 滚动浏览其中包含 Collectionview 的 UITableView 时崩溃

ios - 如何将信息从自定义单元格发送到 View Controller ?

html - 是否有一个简单的解决方案可以快速解析 html 以将各个元素放入它们自己的变量中?

ios - Cosmic Mind - 实现 TabsController 时如何调整 View 大小

iOS:使用 UINavigationBarAppearance 时指定状态栏文本颜色现在 barstyle 被忽略