#import "ViewController.h"
#import <CoreLocation/CoreLocation.h>
@interface ViewController ()<CLLocationManagerDelegate>
// 定位管理对象
@property (nonatomic, strong) CLLocationManager *mgr;
// 指南针
@property (nonatomic, strong) UIImageView *compass;
@end
@implementation ViewController
- (CLLocationManager *)mgr{
if (!_mgr) {
_mgr = [[CLLocationManager alloc] init];
}
return _mgr;
}
- (void)viewDidLoad {
[super viewDidLoad];
// 1. 添加指南针
UIImageView *iv = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"bg_compasspointer"]];
iv.center = CGPointMake(self.view.center.x, self.view.center.y);
[self.view addSubview:iv];
self.compass = iv;
// 2. 成为代理
self.mgr.delegate = self;
// 3. 开始监听
// 开始获取用户方向 --- 不需要授权
// [self.mgr startUpdatingHeading];
}
// 授权状态改变调用这个方法
- (void)locationManager:(CLLocationManager *)manager didChangeAuthorizationStatus:(CLAuthorizationStatus)status
{
if (status == kCLAuthorizationStatusNotDetermined) {
LogYellow(@"正在授权");
}else if ((status == kCLAuthorizationStatusAuthorizedAlways) || (status == kCLAuthorizationStatusAuthorizedWhenInUse)){
[self.mgr startUpdatingHeading];
}else{
LogYellow(@"授权失败");
}
}
#pragma mark - CLLocationManagerDelegate
// 当获取到用的的方向时, 就会调用
- (void)locationManager:(CLLocationManager *)manager didUpdateHeading:(CLHeading *)newHeading
{
/**
magneticHeading 设备与磁北的相对角度
trueHeading 设置与真北的相对角度, 必须和定位一起使用, iOS需要设置的位置来计算真北
真北始终指向地理北极点
磁北对应随着时间变化的地球磁场北极
*/
LogRed(@"%f",newHeading.magneticHeading);
// 1.角度转换成弧度
CGFloat angle = newHeading.magneticHeading * M_PI/ 180.0;
// 2.旋转图片
/**
* 顺时针: 正数
* 逆时针: 负数
*/
// self.compass.transform = CGAffineTransformIdentity;
self.compass.transform = CGAffineTransformMakeRotation(-angle);
}