指南针的设计(ios)

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{
    
}
7251CB54-B515-4BA1-AC32-4D4BCC96B279.png

注:该功能只能在真机上实现,不能再模拟器上运行。

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容