微信摇一摇的代码实现

来源:互联网 发布:网络翻唱歌手胖子 编辑:程序博客网 时间:2024/05/16 01:13

//

//  ViewController.m

//  shuaxin

//

//  Created by SGQ on 16/5/9.

//  Copyright © 2016 GQ. All rights reserved.

//


#import "ViewController.h"

#import <CoreMotion/CoreMotion.h>


@interface ViewController ()

@property (nonnull,strong)CMMotionManager * motionManager;

@end


@implementation ViewController



- (void)viewDidLoad {

    [superviewDidLoad];

    //iOS4之前,加速度计由UIAccelerometer类来负责采集工作,之后由CMMotionManager<Core Motion Framework>管理。

    

    //初始化

   self.motionManager = [[CMMotionManageralloc] init];

    //检查传感器到底在设备上是否可用

    if (self.motionManager.isDeviceMotionAvailable) {

       //更新频率

        self.motionManager.accelerometerUpdateInterval = 0.1;

        //每次更新的回调,线程根据情况而定

        [self.motionManagerstartAccelerometerUpdatesToQueue:[NSOperationQueuemainQueue] withHandler:^(CMAccelerometerData *_Nullable accelerometerData, NSError * _Nullable error) {

            // CMAccelerometerData这个类里面可用的属性只有 @property(readonly, nonatomic) CMAcceleration acceleration;CMAcceleration是一个简单的结构体,xyz分别表示xyz方向的加速度.(国际单位)

           CGFloat x = accelerometerData.acceleration.x;

           CGFloat y = accelerometerData.acceleration.y;

           CGFloat z = accelerometerData.acceleration.z;

            

           NSLog(@"x=%f   y=%f  z=%f ",x,y,z);

            //这里你可以进行判断,比如微信摇一摇,当这个xyz任意一个数值大于1.3(1.3是测试出来的,不能太大或者太小),即可触发某个方法

           if ( x>1.3 || y>1.3 || z>1.3 ) {

               // 摇一摇方法触发

           NSLog(@"用户摇一摇了"); 

            }

        }];

        

    }

    // 要注意的是,在不用self.motionManager,需要[self.motionManager stopAccelerometerUpdates],因为self.motionManager后再线程中不停的请求数据.

    

}


1 0