美文网首页
iOS传感器(指南针、GPS、加速计、摇一摇)

iOS传感器(指南针、GPS、加速计、摇一摇)

作者: 小小土豆dev | 来源:发表于2017-11-23 23:39 被阅读0次

    一:指南针

    #import <CoreLocation/CoreLocation.h>

    CLLocationManager *locManger = [[CLLocationManager alloc] init];

    locManger.delegate = self;

    locManger.headingFilter = 0.1;// 最小变化度数

    [locManger startUpdatingHeading];// 开始更新方向

    // 代理方法

    - (void)locationManager:(CLLocationManager*)manager didUpdateHeading:(CLHeading*)newHeading {

        if(newHeading.magneticHeading == 0) {// 0度表示北方,180度表示南方

            NSLog(@"北方");

        } else if(newHeading.magneticHeading == 180) {

        NSLog(@"南方");

    }}

    二:GPS

    #import <CoreLocation/CoreLocation.h>

    CLLocationManager *locManger = [[CLLocationManager alloc] init];

    self.locationManager.delegate = self;// 设置委托

    [self.locationManager setDesiredAccuracy:CLLocationDistanceMax];// 设置精度为最优

    [self.locationManager setDistanceFilter:(100.0)];// 设置更新的最小距离100米

    [self.locationManager startUpdatingLocation];// 开始更新位置信息

    回调方法

    - (void)locationManager:(CLLocationManager*)manager

    didUpdateLocations:(NSArray*)locations {

    CLLocation *nowLocation = [locations lastObject];// 获取当前位置

    CLLocationDegrees longitutude = newLocation.coordinate.longitude;// 获取经度

    CLLocationDegrees latitude = newLocation.coordinate.latitude;// 获取纬度

    }

    // 计算距离

    -(void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation {  

    double distance = [newLocation distanceFromLocation:oldLocation];   NSLog(@"distance = %lf", distance);

    }

    三:加速计

    1.获得加速计对象

    UIAccelerometer*accelerometer = [UIAccelerometersharedAccelerometer];

    accelerometer.delegate=self;// 设置委托

    // 设置更新间隔时间

    accelerometer.updateInterval=1.0f/30.0f;

    2.回调方法

    - (void)accelerometer:(UIAccelerometer*)accelerometer didAccelerate:(UIAcceleration*)acceleration {

      self.xLabel.text= [NSString stringWithFormat:@"%f",acceleration.x];// 获得x轴原始数据

      self.yLabel= [NSString stringWithFormat:@"%f",acceleration.y];// 获得y轴原始数据

      self.zLabel= [NSString stringWithFormat:@"%f",acceleration.z];// 获得z轴原始数据

    }

    四:摇一摇

    // 在Controller中重写此方法,就可以获取摇一摇事件

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

      if (motion == UIEventSubtypeMotionShake) {

      // 检测到了,手机摇一摇

    }}

    相关文章

      网友评论

          本文标题:iOS传感器(指南针、GPS、加速计、摇一摇)

          本文链接:https://www.haomeiwen.com/subject/lojkvxtx.html