0

Is it possible to request the values of the Accelerometer/Gyroscope without using continuous delegation (like using UIAccelerometerDelegate or something like CMMotionManager startGyroUpdatesToQueue)? I mean, I want to request the values for x, y and z, just once and this as resource-efficient as possible.

thank you.

NANNAV
  • 4,875
  • 4
  • 32
  • 50
Philipp Li
  • 499
  • 6
  • 22

2 Answers2

1

This should work.

CMMotionManager* motionManager = [[CMMotionManager alloc] init];
[motionManager startAccelerometerUpdates];
CMAccelerometerData* data = [motionManager accelerometerData];
while ( data.acceleration.x == 0 )
{
    data = [motionManager accelerometerData];
}
NSLog(@"x = %f, y = %f, z = %f.", data.acceleration.x, data.acceleration.y, data.acceleration.z);

This is just an example of what you could do to make things work. This is a pretty bad idea in my opinion, but it does make things work if you want to get it done.

The code is pretty simple and straightforward, you tell a CMMotionManager to start retrieving data from accelerometer or gyroscope, and then you request the data from it. Here why it's bad, updates have intervals, so for the first few milliseconds, the data retrieved from CMMotionManager is zero-valued. That's what the while loop is for. This type of things should be offloaded to another thread so the UI won't be blocked, but it's even more resource-consuming than UIAccelerometerDelegate and the blocking won't be more than half a second.

Shane Hsu
  • 7,937
  • 6
  • 39
  • 63
  • thank you. that's a interesting piece of code. Why do you think, thats this solution will be more resource-consuming than using UIAccelerometerDelegate? Using UIAccelerometerDelegate processes continuously... but If I need the coordinates just 3-times an hour (event-driven by user action), than your code snippet seems to be the better solution?! – Philipp Li Mar 24 '13 at 11:39
  • By more resource-consuming, I mean if you try to offload this while-loop to a separate NSThread. This code snippet **will** freeze the UI for like half a second, which on older device, might not be such a great experience. I have no such hardware to test it out, but I think you should test it on older hardware. – Shane Hsu Mar 24 '13 at 13:32
0

If you need data only 3 times per hour you can just stop delegation using

accelerometer.delegate = nil;

This should prevent the loss of resources (at least enough to tell system that your app do not needs accelerometer data at the moment)

Victor Laskin
  • 2,577
  • 2
  • 16
  • 10