How to use CMMotionActivityManager and receive updates?

emattiazzi picture emattiazzi · Jan 21, 2014 · Viewed 12.5k times · Source

I want to create an app that can receive and process motion updates in order to understand if the user is stationary, walking, running or is on a transport. I've seen on the reference that CMMotionActivityManager can be useful for me.

The CMMotionActivityManager class provides access to the motion data stored by a device. Motion data reflects whether the user is walking, running, in a vehicle, or stationary for periods of time.

I'm new to app developing and I don't understand how to use the method for starting the updating. The method for doing this is - (void)startActivityUpdatesToQueue:(NSOperationQueue *)queue withHandler:(CMMotionActivityHandler)handler. I don't understand what should i write on handler because the reference says:

handler The block to execute when a change in the current type of motion is detected. For information about the parameters of this block, see CMMotionActivityHandler. This property must not be nil.

My implementation is:

- (IBAction)startButtonPressed:(id)sender {
_motionActivityManager = [[CMMotionActivityManager alloc] init];
[_motionActivityManager startActivityUpdatesToQueue:NSOperationQueueDefaultMaxConcurrentOperationCount withHandler:CMMotionActivityHandler];
}

I've already imported the CoreMotion framework But XCode don't recognize CMMotionActivityHandler, where am I wrong? How can I resolve this problem?

Thanks

Answer

Bhavin picture Bhavin · Jan 21, 2014

Sample Code :

[_motionActivityManager startActivityUpdatesToQueue:[[NSOperationQueue alloc] init]
                                          withHandler:
     ^(CMMotionActivity *activity) {

         dispatch_async(dispatch_get_main_queue(), ^{

             if ([activity walking]) {
                 NSLog(@"walking");
             }
     });
}];