我正构建一个应用程序,每当他通过我的客户商店时都会通知用户。
问题是它有超过20个商店,CLLocationManager允许同时监控多达20个商店。
所以我所做的就是找到距离用户当前位置最近的20家商店,但由于某种原因它是不准确的。
就像第一次运行应用程序时,locationManager正确监控区域。
有人可以查看我的代码并告诉我他是否认为错误?谢谢!
我的代码(滚动查看所有代码):
-(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.userLocation];
float dist2 = [location2 distanceFromLocation:self.userLocation];
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;
NSLog(@"%f,%f",self.userLocation.coordinate.latitude,self.userLocation.coordinate.longitude);
for (int i = 0; i < 20; i++) {
[self.twentyClosestStores addObject:[self.allStores objectAtIndex:i]];
}
Store *nearest=[self.twentyClosestStores firstObject];
}
-(void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray<CLLocation *> *)locations
{
NSLog(@"%f,%f",self.userLocation.coordinate.latitude,self.userLocation.coordinate.longitude);
self.userLocation=self.locationManager.location;
}
-(void)locationManager:(CLLocationManager *)manager didEnterRegion:(CLRegion *)region
{
NSLog(@"Entered");
}
-(void)stopMonitoringStores
{
for (Store *currentStore in self.twentyClosestStores) {
CLCircularRegion *region=[currentStore createCircularRegion];
[self.locationManager stopMonitoringForRegion:region];
}
}
-(void)locationManager:(CLLocationManager *)manager didExitRegion:(CLRegion *)region
{
if (self.allStores.count>=1171) {
[self sortClosestStores];
}
if (self.previousTwentyStores!=nil||self.previousTwentyStores.count==0) {
[self stopMonitoringStores];
}
[self startMonitoringClosestStores];
}
-(void)startMonitoringClosestStores
{
[self stopMonitoringStores];
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];
}
}
你能看错吗?
非常感谢!