我目前正在监视由核心数据支持的几个位置。换句话说,我设置了一个 for 循环,循环遍历核心数据中所有存储的实体,并为所有实体创建一个受监控的区域。
这里的问题是,当进入一个区域时,for 循环会触发多个本地通知。通知的数量几乎直接对应于监控区域的数量。所以我相当有信心这可能是导致错误的原因,但我不是 100% 确定。
我注意到这似乎是区域监控的一个常见问题,但我一直找不到包含 for 循环的示例。
如何在调用 didEnterRegion 时停止触发多个通知?
下面的方法在 viewDidLoad 中被调用。[DataSource sharedInstance].fetchedResultItems 是一个数组,其中填充了来自已获取请求的 fetchedObjects。
-(void)startMonitoringRegions{
if ([self.locationManager respondsToSelector:@selector(requestWhenInUseAuthorization)]) {
[self.locationManager requestWhenInUseAuthorization];
CLAuthorizationStatus authorizationStatus = [CLLocationManager authorizationStatus];
if (authorizationStatus == kCLAuthorizationStatusAuthorizedAlways ||
authorizationStatus == kCLAuthorizationStatusAuthorizedWhenInUse) {
self.locationManager.distanceFilter = 10;
[self.locationManager startUpdatingLocation];
for (POI *items in [DataSource sharedInstance].fetchResultItems){
NSString *poiName = items.name;
NSNumber *poiLatitude = items.yCoordinate;
NSLog(@"value: %@", poiLatitude);
NSNumber *poiLongitude = items.xCoordinate;
NSLog(@"value: %@", poiLongitude);
NSString *identifier = poiName;
CLLocationDegrees latitude = [poiLatitude floatValue];
CLLocationDegrees longitude = [poiLongitude floatValue];
CLLocationCoordinate2D centerCoordinate = CLLocationCoordinate2DMake(latitude, longitude);
self.regionRadius = 10;
self.region = [[CLCircularRegion alloc] initWithCenter:centerCoordinate radius:400 identifier:identifier];
[self.locationManager startMonitoringForRegion:self.region];
NSLog(@"region: %@", self.region);
NSLog(@"monitored regions %@", self.locationManager.monitoredRegions);
}
}
}
}
这是 didEnterRegion 方法
- (void)locationManager:(CLLocationManager *)manager didEnterRegion:(CLRegion *)region{
NSLog(@"entered region!!");
UILocalNotification *localNotification = [[UILocalNotification alloc] init];
if (localNotification) {
localNotification.fireDate = nil;
localNotification.alertBody = [NSString stringWithFormat:@"You are near %@", self.region.identifier];
localNotification.fireDate = [NSDate dateWithTimeIntervalSinceNow:10];
localNotification.timeZone = [NSTimeZone defaultTimeZone];
}
[[UIApplication sharedApplication] scheduleLocalNotification:localNotification];
// [[UIApplication sharedApplication]presentLocalNotificationNow:localNotification];
}