import "ViewController.h"
import <CoreLocation/CoreLocation.h>//注:导入定位框架
@interface ViewController ()<CLLocationManagerDelegate>
{
CLLocationManager *locationManager;
UIImageView *compassView;//指南针视图
}
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
//初始化指南针视图
compassView = [[UIImageView alloc]initWithFrame:self.view.frame];
compassView.contentMode = UIViewContentModeScaleAspectFit;
compassView.image = [UIImage imageNamed:@"指南针.jpg"];
[self.view addSubview:compassView];
if (![CLLocationManager locationServicesEnabled]) {
return;
}
locationManager = [[CLLocationManager alloc]init];
```
// 判断系统版本
// iOS8.0之后 需要向用户请求授权
// if ([[UIDevice currentDevice].systemVersion floatValue]>=8.0) {
//
//// 获取设备方向 可以不向用户请求
// [locationManager requestAlwaysAuthorization];
//}
```
// 设置多少米更新一次
locationManager.distanceFilter = 100;
/*
extern const CLLocationAccuracy kCLLocationAccuracyBest;
extern const CLLocationAccuracy kCLLocationAccuracyNearestTenMeters;
extern const CLLocationAccuracy kCLLocationAccuracyHundredMeters;
extern const CLLocationAccuracy kCLLocationAccuracyKilometer;
extern const CLLocationAccuracy kCLLocationAccuracyThreeKilometers;
*/
//定位精度 越精准 耗电量 越大 越发热
//locationManager.desiredAccuracy = kCLLocationAccuracyHundredMeters;
// 系统会帮你 自动管理 开启 关闭定位功能
//locationManager.pausesLocationUpdatesAutomatically = YES;
locationManager.delegate = self;
// 更新方向
[locationManager startUpdatingHeading];
}
-(void)viewDidDisappear:(BOOL)animated{
[super viewWillDisappear:YES];
}
//当航向 发生改变的时候 调用
- (void)locationManager:(CLLocationManager *)manager
didUpdateHeading:(CLHeading *)newHeading{
// 获得地磁方向
CLLocationDirection direction = newHeading.magneticHeading;
// 角度 = 地磁方向*π/180;M_PI
CGFloat angle = direction*M_PI/180;
NSLog(@"%f",angle);
compassView.transform = CGAffineTransformMakeRotation(-angle);
}
- (void)locationManager:(CLLocationManager *)manager
didFailWithError:(NSError *)error{
}
注:该功能只能在真机上实现,不能再模拟器上运行。