IOS中实现设备摇动检测

这些方法都是在网上看到的,我自己经过测试的就这2种;

1.UIWindow(已测试)

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

{

}

- (void)motionEnded:(UIEventSubtype)motion withEvent:(UIEvent *)event
{
    if (motion == UIEventSubtypeMotionShake )
    {
        //这里可以促发系统震动,或者发送一个通知,进行相应的处理
    }
}

- (void)motionCancelled:(UIEventSubtype)motion withEvent:(UIEvent *)event
{    
}


2. UIViewController(继承自UIResponder - 已测试)

-(BOOL)canBecomeFirstResponder {

    returnself.shakeSyncIsOn;//这里是self拥有的一个变量,通过这个变量来设定知否支持摇动

}

-(void)viewDidAppear:(BOOL)animated {

    [super viewDidAppear:animated];

    if ([selfcanBecomeFirstResponder]==YES)

    {

        NSLog(@"becomeFirstResponder:YES");

   //下面这句代码,不一定非得写到viewDidLoad或者applicationDidFinishLaunch中,这里也可以

        [[UIApplicationsharedApplication] setApplicationSupportsShakeToEdit:YES];

        [selfbecomeFirstResponder];

    }

    else{

        NSLog(@"becomeFirstResponder:NO");

    }

}

- (void)viewWillDisappear:(BOOL)animated {

    [selfresignFirstResponder];

    [super viewWillDisappear:animated];

}

 

#pragma mark - 

#pragma mark - shakeToSync: UIResponder support motion

//开始摇动检测

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

{

    NSLog(@"====== Shake Begins =======");

}

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

{

    NSLog(@"======= Shake Canceled =======");

}

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

{

       if (motion == UIEventSubtypeMotionShake)

      {

           NSLog(@"======== Shake End ========");

    //这里可以添加震动反馈,或者发送一个通知

    //AudioToolBox.framework

     //#import "AudioToolbox/AudioToolbox.h" 

    AudioServicesPlaySystemSound(kSystemSoundID_Vibrate);

      }

}

 

posted @ 2013-02-28 15:37  traximus  阅读(427)  评论(0编辑  收藏  举报