1

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!

2 Answers2

2

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!

0

The problem is this line:

manager.startDeviceMotionUpdates()

Cut it. You will start updates later, when you say:

manager.startDeviceMotionUpdates(to: //...

What's messing you up is saying both.

matt
  • 515,959
  • 87
  • 875
  • 1,141
  • Ok, now I'm aware of that - as U can see, I cut that in my solution. – Adrian Krzyżowski Oct 19 '16 at 21:16
  • And to be honest - I tried removing this line before (leaving only manager.startDeviceMotionUpdates(to: //...) and even though it didn't work... – Adrian Krzyżowski Oct 19 '16 at 21:20
  • I am looking right at your original code and at your "solution". There is _no relevant difference_ between them other than the extra `manager.startDeviceMotionUpdates()` line. – matt Oct 19 '16 at 22:24