iOSiOS实战

iOS 指南针

2015-11-12  本文已影响1578人  iOS_成才录
指南针图片.png

一、实现思路:

二、实现步骤:

import <CoreLocation/CoreLocation.h>

``` 

+2.创建CLLcationManager对象,并设置代理
objc _locationM = [[CLLocationManager alloc] init]; _locationM.delegate = self;

[_locationM startUpdatingHeading];
```

-(void)locationManager:(nonnull CLLocationManager *)manager didUpdateHeading:(nonnull CLHeading *)newHeading
{
// 获取当前设备朝向(磁北方向)
CGFloat angle = newHeading.magneticHeading;

    // 转换成为弧度
     CGFloat radian = angle / 180.0 * M_PI;

   // 反向旋转指南针
     [UIView animateWithDuration:0.5 animations:^{
         self.compassView.transform = CGAffineTransformMakeRotation(-radian);
    }];
 }

### 注意
+ 注意: 获取用户的设备朝向,不需要用户进行定位授权 
+ 0.使用之前先判断方向服务是否可用
+ 1.获取手机设备朝向(使用的是”磁力计”传感器)不需要用户定位授权
+ 2.设备朝向(使用的是”磁力计”传感器)和航向course的区别(gps定位确定)

### 应用场景
- 1.指南针
- 2.一些比较有创意的app(“随便走”,是我见过把传感器利用的最有创意的一个app)


## 三、代码实现

```objc
#import "ViewController.h"
#import <CoreLocation/CoreLocation.h>

@interface ViewController ()<CLLocationManagerDelegate>

@property (weak, nonatomic) IBOutlet UIImageView *compassView;

/** 位置管理者 */
@property (nonatomic, strong) CLLocationManager *locationM;


@end

@implementation ViewController


#pragma mark -懒加载
-(CLLocationManager *)locationM
{
  if (!_locationM) {
      _locationM = [[CLLocationManager alloc] init];
      _locationM.delegate = self;
  }
  return _locationM;
}

- (void)viewDidLoad {

  // 获取当前设备朝向
  [self.locationM startUpdatingHeading];
}


#pragma mark -CLLocationManagerDelegate

// 已经更新到用户设备朝向时调用
-(void)locationManager:(CLLocationManager *)manager didUpdateHeading:(CLHeading *)newHeading
{

  // magneticHeading : 距离磁北方向的角度
  // trueHeading : 真北
  // headingAccuracy : 如果是负数,代表当前设备朝向不可用
  if (newHeading.headingAccuracy < 0) {
      return;
  }
  
  // 角度
  CLLocationDirection angle = newHeading.magneticHeading;
  
  // 角度-> 弧度
  double radius = angle / 180.0 * M_PI;
  
  // 反向旋转图片(弧度)
  [UIView animateWithDuration:0.5 animations:^{
          self.compassView.transform = CGAffineTransformMakeRotation(-radius);
  }];
}
@end
上一篇 下一篇

猜你喜欢

热点阅读