【发布时间】:2015-10-25 00:12:48
【问题描述】:
我目前正在监控由核心数据支持的几个位置。 换句话说,我设置了一个 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];
}
【问题讨论】:
标签: ios localnotification region-monitoring