我在我的 iOS 应用程序中使用位置服务,即区域监控,这是我的代码
//this for creating region
-(void)createRegion
{
[dictionary setValue:@"23 St, New York" forKey:@"title"];
[dictionary setValue:[NSNumber numberWithDouble:40.742878] forKey:@"latitude"];
[dictionary setValue:[NSNumber numberWithDouble:-73.992821] forKey:@"longitude"];
[dictionary setValue:[NSNumber numberWithDouble:(300.0)] forKey:@"radius"];
[regionArray addObject:[self mapDictionaryToRegion:dictionary]];
[self initializeRegionMonitoring:regionArray];
}
- (CLRegion*)mapDictionaryToRegion:(NSDictionary*)dictionary {
NSString *title = [dictionary valueForKey:@"title"];
CLLocationDegrees latitude = [[dictionary valueForKey:@"latitude"] doubleValue];
CLLocationDegrees longitude =[[dictionary valueForKey:@"longitude"] doubleValue];
CLLocationCoordinate2D centerCoordinate = CLLocationCoordinate2DMake(latitude, longitude);
CLLocationDistance regionRadius = [[dictionary valueForKey:@"radius"] doubleValue];
return [[CLRegion alloc] initCircularRegionWithCenter:centerCoordinate
radius:regionRadius
identifier:title];
}
- (void) initializeRegionMonitoring:(NSArray*)geofences {
if(![CLLocationManager regionMonitoringAvailable]) {
// [self showAlertWithMessage:@"This app requires region monitoring features which are unavailable on this device."];
return;
}
for(CLRegion *geofence in geofences) {
[_locationManager startMonitoringForRegion:geofence];
}
}
- (void)locationManager:(CLLocationManager *)manager didEnterRegion:(CLRegion *)region {
NSLog(@"entered region %@",region.identifier);
}
- (void)locationManager:(CLLocationManager *)manager didExitRegion:(CLRegion *)region {
NSLog(@"exited region %@",region.identifier);
}
当应用程序在前台时它工作正常。它向我显示日志:“输入区域..”和“退出区域..”,但是当应用程序进入后台时,相同的日志在几分之一秒内打印两次,即委托方法调用两次,我不需要,有什么办法可以避免调用 2 次? 还是在创建或监视区域时犯了任何错误?请帮助我..提前谢谢..