How do I retrieve accelerometer data correctly with Swift in iOS?

自作多情 提交于 2019-12-03 04:18:29
Xiaojun

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

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)
     }
}
gihanshox

you can get value of x or y or z and print alert of value you want

motionManager.accelerometerUpdateInterval = 5.0
motionManager.startAccelerometerUpdates(to: OperationQueue.current!) { (data, error) in
        if let myData = data{
            print(myData)
            if myData.acceleration.y < -0.2{
                let alert = UIAlertController(title: "Message ", message: "new text", preferredStyle: UIAlertControllerStyle.alert)
                alert.addAction(UIAlertAction(title: "OK", style: UIAlertActionStyle.default, handler: nil))
                self.present(alert, animated: true, completion: nil)

            }
        }
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!