Friday, 8 January 2016

Motion Detection

Motion Detection


add framework :-  CoreMotion.framework

.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 allocinit];
    [motionActivityManager startActivityUpdatesToQueue:[[NSOperationQueuealloc]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 allocinitWithTitle:@"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:

Post a Comment