您當前位置>首頁 » 新聞資訊 » 技(jì)術(shù)分(fēn)享 >
IOS開(kāi)發檢測設備搖動
發表時(shí)間(jiān):2021-1-10
發布人(rén):葵宇科(kē)技(jì)
浏覽次數(shù):50
設備搖動檢測的(de)兩種方法簡單的(de)記錄下(xià)
方法一(yī)
首先在delegate中添加
- (BOOL)application:(UIApplication ≈≈↕*)application didFinishLaunchingWithOptions:(N™→÷SDictionary *)launchOptions
{
// Override point for cuεε©stomization after application laβ&&¶unch
//添加檢測晃動
application.a₩€pplicationSupportsShakeToEdit = YESπ× ×;
}
其次在需要(yào)檢測的(de)ViewController中添加
//檢測手機(jī)晃動
-(BOOL)canBecomeFirstResponder
{
return YES;
}
- (void)viewWillDisappear:(BOOL)animated {
[self resignFirstRespo★δα↔nder];
[super viewWillDisap₹£≤♣pear:animated];
}
- (void)motionEnded:(UIEventSubtype)motion with€§βEvent:(UIEvent *)event
{
if (motion == UIEventSubt ✔ypeMotionShake)
{
UIAlertView *alertVi¥δα©ew = [[UIAlertView alloc]initWithTitle:@&q∑↔±uot;提示" message:@"恭喜你(nǐ)獲得(d"φe)100-5優惠劵一(yī)張" delegate:self cancelBut✘λφαtonTitle:@"關閉" otherButtonTitles:¥" nil];
±×π
[alert×₹View show];
&nbα ©δsp;
NSLog(@"檢測到(dα✔ào)晃動");
}
}
-(void)prarGotProblem:(NSString *)problemTitle wi§Ω thDetails:(NSString *)problemDetails
{
[self alert:problemTitle wit<€ ™hDetails:problemDetails];
}
方法二使用(yòng)CoreMotion
引入需要(yào)的(de)頭文(wén)件(jiàn)
#import <CoreMotion/CoreMotion.h>
下(xià)需要(yào)檢測的(de) viewDidLoad初始化(↕'©→huà)CMMotionManager 同時(shí)啓動一(yī)個(gè)N∏≠☆<STimer檢測X、Y、Z軸的(de)變化(huà)
- (void)viewDidLoad {
[super viewDσ₩idLoad];
// Do any additional≠¶ setup after loading the view.
NSTimer *AutoTimer = [NSTimer s✘✘↑→cheduledTimerWithTimeInterval:1✘∏.0/60.0 target:self selector:@selector($≥ autoChange) userInfo:nil repeatε♣φs:YES];
_manager = [[CM> MotionManager alloc]init]¥♥→;
_manager.acceleroγβ€meterUpdateInterval=1.0/60.0;
[_manager startAc§☆€≠celerometerUpdates];
}
-(void)autoChange
{
//根據自(zì)己需求調節¶↓x y z
if (fabsf(_manager.accelerometerD¶δ←∑ata.acceleration.x) >₽★♥ 1.0 || fabsf(_manager.acceleromete★π≥✘rData.acceleration.y) > 1.2 |λπ| fabsf(_manager.accelerometerData.acceleratio↔←§n.z) > 0.5)
{
NSLog(σ♣@"我晃動了(le) 。。。。。");
}
}
注:方法一(yī)中晃動幅度大(dà)的(de)情況下(xià)才會(huì)調γ₽ "用(yòng),方法二中可(kě)以根據自(zì)己的(de)需要(yào)調節