首页 > 代码库 > IOS开发检测设备摇动

IOS开发检测设备摇动

设备摇动检测的两种方法简单的记录下


方法一

首先在delegate中添加

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions

{

    // Override point for customization after application launch

    

    //添加检测晃动

    application.applicationSupportsShakeToEdit =YES;

}


其次在需要检测的ViewController中添加


//检测手机晃动

-(BOOL)canBecomeFirstResponder

{

    return YES;

}


- (void)viewWillDisappear:(BOOL)animated {

    [self resignFirstResponder];

    [super viewWillDisappear:animated];

}


- (void)motionEnded:(UIEventSubtype)motion withEvent:(UIEvent *)event

{

    if (motion == UIEventSubtypeMotionShake)

    {

        

        UIAlertView *alertView = [[UIAlertView alloc]initWithTitle:@"提示" message:@"恭喜你获得100-5优惠劵一张" delegate:self cancelButtonTitle:@"关闭" otherButtonTitles: nil];

        

        [alertView show];

        

        NSLog(@"检测到晃动");

    }

}


-(void)prarGotProblem:(NSString *)problemTitle withDetails:(NSString *)problemDetails

{

    [self alert:problemTitle withDetails:problemDetails];

}


方法二使用CoreMotion


引入需要的头文件

#import <CoreMotion/CoreMotion.h>


下需要检测的 viewDidLoad初始化CMMotionManager 同时启动一个NSTimer检测X、Y、Z轴的变化


- (void)viewDidLoad {

    [superviewDidLoad];

    // Do any additional setup after loading the view.

    NSTimer *AutoTimer = [NSTimerscheduledTimerWithTimeInterval:1.0/60.0target:selfselector:@selector(autoChange)userInfo:nilrepeats:YES];


    _manager = [[CMMotionManageralloc]init];

    _manager.accelerometerUpdateInterval=1.0/60.0;

    [_managerstartAccelerometerUpdates];

}

-(void)autoChange

{

    //根据自己需求调节x y z

    if (fabsf(_manager.accelerometerData.acceleration.x) > 1.0 || fabsf(_manager.accelerometerData.acceleration.y) > 1.2 || fabsf(_manager.accelerometerData.acceleration.z) > 0.5)

    {

        NSLog(@"我晃动了。。。。。");

    }

}



注:方法一中晃动幅度大的情况下才会调用,方法二中可以根据自己的需要调节





IOS开发检测设备摇动