iOS CoreLocation之区域监测

CoreLocation的区域监测,下图来自疯狂iOS讲义

区域监测示意图

1.引CoreLocation框架,导入头文件

#import <CoreLocation/CoreLocation.h>

2.添加定位管理为成员变量,添加延迟加载

@property (nonatomic,strong) CLLocationManager *locMgr;
 1 /**
 2  *  懒加载
 3  */
 4 - (CLLocationManager *)locMgr
 5 {
 6     if (_locMgr == nil) {
 7         _locMgr = [[CLLocationManager alloc]init];
 8         _locMgr.delegate = self;
 9     }
10     return _locMgr;
11 }

3.开启区域监测

 1 - (void)viewDidLoad
 2 {
 3     [super viewDidLoad];
 4 
 5     // 设置中心
 6     CLLocationCoordinate2D coordinate = CLLocationCoordinate2DMake(39, 116);
 7     // 设置半径
 8     CLLocationDistance distance = 500;
 9     // 创建监测区域
10     CLRegion *region = [[CLCircularRegion alloc]initWithCenter:coordinate radius:distance identifier:@"region"];
11     
12     // 开始区域检测
13     [self.locMgr startMonitoringForRegion:region];
14 }

4.添加代理方法

 1 #pragma mark -CLLocationManagerDelegate
 2 - (void)locationManager:(CLLocationManager *)manager didStartMonitoringForRegion:(CLRegion *)region
 3 {
 4     NSLog(@"成功开启区域监测");
 5 }
 6 
 7 - (void)locationManager:(CLLocationManager *)manager didEnterRegion:(CLRegion *)region
 8 {
 9     NSLog(@"你已进入监测区域");
10 }
11 
12 - (void)locationManager:(CLLocationManager *)manager didExitRegion:(CLRegion *)region
13 {
14     NSLog(@"你已经离开监测区域");
15     
16     // 关闭区域监测
17     if ([region.identifier  isEqual: @"region"]) {
18         [self.locMgr stopMonitoringForRegion:region];
19     }
20 
21 }
原文地址:https://www.cnblogs.com/oumygade/p/4168172.html