CMMotionManager - getting heading using CMMotionMa

2019-08-10 21:33发布

问题:

I have managed to get compass heading using CLLocationManager but because my app already uses CMMotionManager I would like to measure heading using exclusively CMMotionManager.

Like all Apple vague documentation, you have to guess how to use their APIs.

I have tried to use this to measure heading

[self.motionManager setMagnetometerUpdateInterval:1.0/30.0]; //30 Hz

[self.motionManager startMagnetometerUpdatesToQueue:[NSOperationQueue currentQueue] withHandler:^(CMMagnetometerData *magnetometerData, NSError *error) {
    CMMagneticField compass = magnetometerData.magneticField;
    NSLog(@"x: %f  y:%f  z:%f", compass.x, compass.y, compass.z);
}];

the problem is that this block runs just a few seconds then stop running.

Is there any example of how to measure heading using CMMotionManager exclusively?

thanks.

回答1:

Apparently the best way to do it is using CoreLocation, until Apple creates decent documentation.



回答2:

Without actually attempting this, I would recommend using [NSOperationQueue mainQueue] instead of currentQueue. Typically, you only call currentQueue from within an operation to obtain a reference to the queue that started it.



回答3:

I would suggest that you not call start...UpdatesToQueue:withHandler:. This requires use of a background thread and can be very tricky to manage. You are probably just gunking everything up on the main thread. It's an advanced technique, and you don't need it.

Instead, just start and then use an NSTimer or similar to poll the CMMotionManager repeatedly.