【发布时间】:2016-05-05 21:54:19
【问题描述】:
我有一个应用程序,它会在用户每次接近我客户的一家商店时通知用户。有20多家商店,所以我有一个功能,可以获取用户的位置并找到离他最近的20家商店并开始监控这些商店的位置,每次用户移动时,应用程序都会再次找到最近的20家商店,删除从监控以前的商店开始监控新的商店。
由于某种原因,它不起作用,如果你们中的一个(或更多:))能帮助我找到问题,我会很高兴,谢谢!!
myCode(滚动查看完整代码):
注意:CLLocationManager 在 AppDelegate.m 上创建,它的委托是这个类 (UIViewController)。
-(void)sortClosestStores
{
[self.allStores sortUsingComparator:^NSComparisonResult(id _Nonnull obj1, id _Nonnull obj2) {
CLLocation *location1=[[CLLocation alloc] initWithLatitude:((Store*)obj1).geoPoint.latitude longitude:((Store*)obj1).geoPoint.longitude];
CLLocation *location2=[[CLLocation alloc] initWithLatitude:((Store*)obj2).geoPoint.latitude longitude:((Store*)obj2).geoPoint.longitude];
float dist1 =[location1 distanceFromLocation:self.locationManager.location];
float dist2 = [location2 distanceFromLocation:self.locationManager.location];
if (dist1 == dist2) {
return NSOrderedSame;
}
else if (dist1 < dist2) {
return NSOrderedAscending;
}
else {
return NSOrderedDescending;
}
}];
if (self.twentyClosestStores==nil) {
self.twentyClosestStores=[NSMutableArray array];
}
if (self.previousTwentyStores==nil) {
self.previousTwentyStores=[NSMutableArray array];
}
self.previousTwentyStores=self.twentyClosestStores;
self.twentyClosestStores=[NSMutableArray array];
for (int i = 0; i < 20; i++) {
[self.twentyClosestStores addObject:[self.allStores objectAtIndex:i]];
}
}
-(void)startMonitoringClosestStores
{
if (![CLLocationManager isMonitoringAvailableForClass:[CLCircularRegion class]]) {
NSLog(@"Monitoring is not available for CLCircularRegion class");
}
for (Store *currentStore in self.twentyClosestStores) {
CLCircularRegion *region=[currentStore createCircularRegion];
[self.locationManager startMonitoringForRegion:region];
}
}
-(void)stopMonitoringStores
{
for (Store *currentStore in self.previousTwentyStores) {
CLCircularRegion *region=[currentStore createCircularRegion];
[self.locationManager stopMonitoringForRegion:region];
}
}
-(void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray<CLLocation *> *)locations
{
if (self.allStores!=nil) {
[self sortClosestStores];
[self stopMonitoringStores];
[self startMonitoringClosestStores];
}
}
-(void)locationManager:(CLLocationManager *)manager didEnterRegion:(CLRegion *)region
{
NSLog(@"Entered"); //Not called even when the user enters one of the regions.
}
你能帮帮我吗?谢谢!
【问题讨论】:
-
什么不起作用? CLLocationManager,还是您最近的商店的标识?
-
@CharlesThierry 当用户接近一个未被调用的区域
locationManager: didEnterRegion:。 -
当我尝试在后台线程上设置 CLLocationManager 时,发生了类似的事情。也许尝试从主线程调用你的代码?
-
@CharlesThierry 它在主线程上
标签: ios objective-c iphone cocoa-touch cllocationmanager