IOS开发检测设备摇动 - 新闻资讯 - 云南小程序开发|云南软件开发|云南网站建设-昆明葵宇信息科技有限公司

159-8711-8523

云南网建设/小程序开发/软件开发

知识

不管是网站,软件还是小程序,都要直接或间接能为您产生价值,我们在追求其视觉表现的同时,更侧重于功能的便捷,营销的便利,运营的高效,让网站成为营销工具,让软件能切实提升企业内部管理水平和效率。优秀的程序为后期升级提供便捷的支持!

您当前位置>首页 » 新闻资讯 » 技术分享 >

IOS开发检测设备摇动

发表时间:2021-1-10

发布人:葵宇科技

浏览次数:30


设备摇动检测的两种方法简单的记录下
方法一
首先在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 {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    NSTimer *AutoTimer = [NSTimer scheduledTimerWithTimeInterval:1.0/60.0 target:self selector:@selector(autoChange) userInfo:nil repeats:YES];
    _manager = [[CMMotionManager alloc]init];
    _manager.accelerometerUpdateInterval=1.0/60.0;
    [_manager startAccelerometerUpdates];
}


-(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(@"我晃动了 。。。。。");
    }
}
注:方法一中晃动幅度大的情况下才会调用,方法二中可以根据自己的需要调节


相关案例查看更多