У меня есть приложение, которое будет уведомлять пользователя каждый раз, когда он подходит к одному из магазинов моего клиента. Есть более 20 магазинов, поэтому у меня есть функция, которая берет местоположение пользователя и находит для него 20 ближайших магазинов и начинает отслеживать местоположение этих магазинов, каждый раз, когда пользователь перемещается, приложение снова находит 20 ближайших магазинов, удаляет предыдущие магазины отслеживают и запускают мониторинг новых.Мониторинг местоположения CLLocationManager не работает должным образом
По какой-то причине это не сработает, я буду рад, если один из вас (или больше :)) поможет мне найти проблему, спасибо!
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
@CharlesThierry Когда пользователь подходит к региону 'locationManager: didEnterRegion:' не вызывается. –
Что-то подобное случилось со мной, когда я попытался настроить CLLocationManager на фоновый поток. Может быть, попробуйте позвонить вам код из основного потока? – CharlesThierry