如何在iOS中使用Swift正确检索加速计数据

如何在iOS中使用Swift正确检索加速计数据

本文介绍了如何在iOS中使用Swift正确检索加速计数据?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

限时删除!!

我正在尝试从iPhone的加速度计(我自己的iPhone 5s)中记录数据,并使用字符串(格式:%。2f,数据)其中data是我要记录的特定轴的值。为此,我设置了CMMotionManager并开始记录加速度计数据,我有一个定时器,可以不断更新标签中的文本。但是,我从Xcode收到错误:致命错误:在展开Optional值时意外发现nil。以下是相关代码:

I am trying to record the data from the iPhone's accelerometer (my own iPhone 5s) and set a label on the screen to that data using String(format: "%.2f", data) where data is the value for the specific axis I want to record. To do this I set up a CMMotionManager and began recording accelerometer data, and I have a timer that constantly updates the text in the label. However, I am getting an error from Xcode: "fatal error: unexpectedly found nil while unwrapping an Optional value". Here is the relevant code:

override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view, typically from a nib.

    //if accelerometer can be used, start it
    if (motionManager.accelerometerAvailable) {

        motionManager.accelerometerUpdateInterval = 0.1

        motionManager.startAccelerometerUpdates()
        let timer = NSTimer.scheduledTimerWithTimeInterval(0.1, target: self, selector: Selector("update"), userInfo: nil, repeats: true)
    }



}

func update () {
    if (motionManager.accelerometerActive) {

        accelX.text = String(format: "%.2f", motionManager.accelerometerData.acceleration.x)
    }

}

当我将accelX.text赋值更改为简单字符串时,错误停止,因此我认为创建错误的可选变量与加速度计有关。然而,据我所知,如果你有任何建议,或者我完全错了,并且有更好更简单的方法,如果你帮助我,我一定会很感激。

The error stops when I change the accelX.text assignment to a simple string, so I think the optional variable creating the error is something to do with the accelerometer. That's as far as I know, however, so if you have any suggestions, or if I'm doing it completely wrong and there's a better and easier way, I will definitely appreciate it if you help me out.

推荐答案

NSHipster有一篇很好的文章来讨论核心议案:

NSHipster has a good article to talk about the core motion: http://nshipster.com/cmdevicemotion/

使用动态数据定期更新UI的更好方法是使用如下所示的模式如下:

A better way to regularly update UI with motion data is to use the patter as shown in below:

if manager.accelerometerAvailable {
     manager.accelerometerUpdateInterval = 0.1
     manager.startAccelerometerUpdatesToQueue(NSOperationQueue.mainQueue()) {
     [weak self] (data: CMAccelerometerData!, error: NSError!) in
          accelX.text = String(format: "%.2f", data.acceleration.x)
     }
}

这篇关于如何在iOS中使用Swift正确检索加速计数据?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

1403页,肝出来的..

09-06 07:48