Adrian Krzyżowski Adrian Krzyżowski - 1 month ago 24
Swift Question

CMDeviceMotion data access

I have a problem with access to CMDeviceMotion data. I have everything what is needed included, but my startDeviceMotionUpdates function seems to be passed over (I think that something's wrong with handler). Here is my code:

let manager = CMMotionManager()
if manager.isDeviceMotionAvailable {
manager.startDeviceMotionUpdates()
manager.deviceMotionUpdateInterval = 0.1
manager.startDeviceMotionUpdates(to: OperationQueue.current!, withHandler: {
(data, error) -> Void in
self.digit.text = String (describing: data!.gravity.z)
self.digit2.text = String (describing: data!.gravity.y)
self.digit3.text = String (describing: data!.gravity.z)
})


digit, digit2 and digit3 are edit text fields, where I want my gravity data written into. Everything is tested on iPhone 6 - deviceMotion is aviable and active. I managed to access data without startMotionUpdates function, but i got only NIL value. Any idea what is wrong? Thanks!

Answer

Ok, I got this. To access Core Motion in Swift 3.0 (using CMDeviceMotion class in my case, but can also be CMGyroData or CMAccelerometerData):

let manager = CMMotionManager()
if manager.isDeviceMotionAvailable {
        manager.deviceMotionUpdateInterval = 0.05 //The lower the interval is, the faster motion data is read 
        manager.startDeviceMotionUpdates(to: OperationQueue.current!, withHandler: {
            (motion: CMDeviceMotion?, Error) -> Void in

            //Do whatever U want with data provided by CMDeviceMotion

            }
        })
    }
    else{
        print("Core Motion access denied")
    }

And don't forget to stop retrieving data from Core Motion if don't needed any more like for example

ovveride func viewWillDisappear(_ animated: Bool) {
manager.stopDeviceMotionUpdates()
}

Basically, my main problem was with the handler implementation. Hope it helps!