IOS開發檢測裝置搖動

來源:互聯網
上載者:User

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


下需要檢測的 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(@"我晃動了。。。。。");

}

}



註:方法一中晃動幅度大的情況下才會調用,方法二中可以根據自己的需要調節





聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.