我正在开发一款iPhone应用程序,我必须监控超过20个区域。
开发环境:Xcode(版本8.3.2)
IOS 10.3
请看下面的代码:
我初始化我的位置管理员:
- (id)init {
self = [super init];
if(self != nil) {
self.locationManager = [[CLLocationManager alloc] init];
// self.locationManager.distanceFilter = 100; // meters
self.locationManager.allowsBackgroundLocationUpdates = YES;
self.locationManager.delegate = self;
self.locationManager.desiredAccuracy = kCLLocationAccuracyBestForNavigation;
}
return self;
}
然后我开始使用以下代码更新位置:
- (void)startUpdatingLocation
{
NSLog(@"Starting location updates");
// Turn on location updates for accuracy and so processing can happen in the background.
[self.locationManager stopUpdatingLocation];
[self.locationManager startUpdatingLocation];
// Turn on significant location changes to help monitor the current region.
[self.locationManager startMonitoringSignificantLocationChanges];
}
- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations
{
if (locations.count > 0) {
//stop all monitored region
for (CLRegion *monitored in [self.locationManager monitoredRegions]){
[self.locationManager stopMonitoringForRegion:monitored];
}
CLLocation *location = locations[0];
NSArray *allGeoFences = [self getAllGeoFences];
NSMutableArray *sortedFences = [[NSMutableArray alloc] init];
// add distance to each fence to be sorted
for (locationInterface *geofence in allGeoFences) {
// create a CLLocation object from my custom object
//CLLocationCoordinate2D coordinate = CLLocationCoordinate2DMake(geofence.region., geofence.longitude);
CLLocation *fenceLocation = [[CLLocation alloc] initWithLatitude:
geofence.region.center.latitude
longitude:geofence.region.center.longitude];
// calculate distance from current location
CLLocationDistance distance = [location distanceFromLocation:fenceLocation];
// save distance so we can filter array later
geofence.distance = distance;
[sortedFences addObject:geofence];
}
// sort our array of geofences by distance and add we can add the first 20
NSSortDescriptor *sortByName = [NSSortDescriptor sortDescriptorWithKey:@"distance" ascending:YES];
NSArray *sortDescriptors = [NSArray arrayWithObject:sortByName];
NSArray *sortedArray = [sortedFences sortedArrayUsingDescriptors:sortDescriptors];
//get nearest 20 regions
NSMutableArray *nearestRegions = [[NSMutableArray alloc] init];
for (int i = 1; i <= 20; i++) {
[nearestRegions addObject:sortedArray[i]];
locationInterface* monitorRegion = sortedArray[i];
[self.locationManager startMonitoringForRegion:monitorRegion.region] ;
}
}
}
当我收到didUpdateLocations时,首先我停止所有受监控的区域,之后我找到20个最近的位置,并开始监控最近的20个位置。
我面临的问题是 monitoredRegions 总是返回nil。这就是为什么我无法停止监控区域,我的新添加的区域被忽略。请帮助我。