Monday, 22 June 2015

Motion Detection for iOS

.h File :
#import <CoreMotion/CMMotionActivityManager.h>
#import <CoreMotion/CMMotionActivity.h>
#import <CoreMotion/CMStepCounter.h>

@interface ViewController : UIViewController
{
    CMMotionActivityManager *motionActivityManager;
}

@end


.m File :
View DidLoad or ViewWillAppear
[self check_MotionDetector];

#pragma mark - Motion Detection
-(void)check_MotionDetector
{
    motionActivityManager = [[CMMotionActivityManager alloc] init];
    [motionActivityManager startActivityUpdatesToQueue:[[NSOperationQueue alloc]init]withHandler:^(CMMotionActivity *activity) {
        dispatch_async(dispatch_get_main_queue(), ^{
            if ([activity running])
            {
                [self doExit:@"Automotive"];
            }
            else if ([activity cycling])
            {
                [self doExit:@"Automotive"];
            }
            else if ([activity automotive])
            {
                [self doExit:@"Automotive"];
            }
        });
    }];
}

-(void)doExit:(NSString *)MotionType
{
    if ([MotionType isEqualToString:@"Automotive"])
    {
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Confirmation"
                                                        message:@"Do you drive the car?"
                                                       delegate:self
                                              cancelButtonTitle:@"No"
                                              otherButtonTitles:@"Yes", nil];
        [alert show];
        [alert setTag:100];
    }
}

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if (alertView.tag == 100)
    {
        if (buttonIndex == 0)
        {
            [motionActivityManager stopActivityUpdates];
        }
        else if (buttonIndex == 1)
        {
            //home button press programmatically
            UIApplication *app = [UIApplication sharedApplication];
            [app performSelector:@selector(suspend)];
            
            //wait 2 seconds while app is going background
            [NSThread sleepForTimeInterval:1.0];
            
            //exit app when app is in background
            exit(0);
        }
    }
}

No comments: