iOS: предупредить пользователя об определенной географической области (широта, долгота)
Я пытаюсь реализовать функцию Geo location
для пользователя я статически настраиваю latitude
а также longitude
информация, когда приложение запускается, если пользователь находится в этой области, я показываю сообщение, что "Вы были доставлены в офис", иначе "Вы выходите из офиса". Я реализовал приведенный ниже код для достижения этой цели, я пытался перемещаться по ступеням и на транспортных средствах, но в обоих случаях это всегда показывает, что "Вы были доставлены в офис", однако я был в 2 км от этого места! Я думаю, что проблема в сравнении данных Geo в CLLocationManager
делегировать.
- (void) startUpdateUserLocation
{
if(!locationManager)
locationManager = [[CLLocationManager alloc] init];
locationManager.delegate = self;
locationManager.distanceFilter = kCLDistanceFilterNone;
locationManager.desiredAccuracy = kCLLocationAccuracyBestForNavigation;
// [locationManager startUpdatingLocation];
CLLocationCoordinate2D coord = CLLocationCoordinate2DMake(latitude, longitude);
CLRegion *region = [[CLRegion alloc] initCircularRegionWithCenter:coord radius:kCLDistanceFilterNone identifier:@"identifier"];
[locationManager startMonitoringForRegion:region];
}
- (void)viewDidLoad
{
[super viewDidLoad];
latitude = 23.076289;
longitude = 72.508129;
}
- (void) viewDidAppear:(BOOL)animated
{
[super viewDidAppear:animated];
MKCoordinateRegion region;
region.center = mapView.userLocation.coordinate;
region.span = MKCoordinateSpanMake(0.25, 0.25);
region = [mapView regionThatFits:region];
[mapView setRegion:region animated:YES];
lblCurrentCoords.text = [NSString stringWithFormat:@"lat %f lon %f",mapView.userLocation.coordinate.latitude,mapView.userLocation.coordinate.longitude];
[self startUpdateUserLocation];
}
- (void)locationManager:(CLLocationManager *)manager
didEnterRegion:(CLRegion *)region __OSX_AVAILABLE_STARTING(__MAC_10_7,__IPHONE_4_0)
{
[listOfPoints addObject:manager.location];
[tablePoints reloadData];
/*
* locationManager:didEnterRegion:
*
* Discussion:
* Invoked when the user enters a monitored region. This callback will be invoked for every allocated
* CLLocationManager instance with a non-nil delegate that implements this method.
*/
lblLocationStatus.text = @"You're in office area!...";
}
- (void)locationManager:(CLLocationManager *)manager
didExitRegion:(CLRegion *)region __OSX_AVAILABLE_STARTING(__MAC_10_7,__IPHONE_4_0)
{
/*
* locationManager:didExitRegion:
*
* Discussion:
* Invoked when the user exits a monitored region. This callback will be invoked for every allocated
* CLLocationManager instance with a non-nil delegate that implements this method.
*/
lblLocationStatus.text = @"You're going out from office area!...";
}
- (void)locationManager:(CLLocationManager *)manager
didStartMonitoringForRegion:(CLRegion *)region __OSX_AVAILABLE_STARTING(__MAC_TBD,__IPHONE_5_0)
{
/*
* locationManager:didStartMonitoringForRegion:
*
* Discussion:
* Invoked when a monitoring for a region started successfully.
*/
lblLocationStatus.text = @"Start monitoring...";
}
- (void)locationManager:(CLLocationManager *)manager
monitoringDidFailForRegion:(CLRegion *)region
withError:(NSError *)error __OSX_AVAILABLE_STARTING(__MAC_10_7,__IPHONE_4_0)
{
/*
* locationManager:monitoringDidFailForRegion:withError:
*
* Discussion:
* Invoked when a region monitoring error has occurred. Error types are defined in "CLError.h".
*/
lblLocationStatus.text = @"Stop monitoring...";
}
Я пытаюсь выполнить следующие вещи!
- Если пользователь вошел в гео локацию, он должен быть "бдительным". --- Как сопоставить местоположение?
- Если вы перемещаетесь в пределах этого географического местоположения, тогда код должен отслеживать эту активность! --- Нужно установить желаемое свойство точности?
- Я хочу, чтобы мой код постоянно проверял местоположение пользователя Geo, как мне это сделать? --- нужно вызвать функцию в
NSTimer
?
Я нашел много вопросов на SO, задаваемых о том же самом, но никто не совпал с ответами! Кто-то, пожалуйста, направьте меня, иду ли я в правильном направлении или нет, так как этот код не отображается!:)
1 ответ
Похоже, вы должны вместо этого использовать мониторинг региона, который сообщает вам, когда пользователь входит или выходит из круговой области. Установите это с startMonitoringForRegion:
и реализовать CLLocationManagerDelegate
методы
– locationManager:didEnterRegion:
– locationManager:didExitRegion:
– locationManager:monitoringDidFailForRegion:withError:
– locationManager:didStartMonitoringForRegion:
Если у вас возникли проблемы с поступлением неверных данных о местоположении, проверьте возраст CLLocation
в locationManager:didUpdateLocations:
или же locationManager:didUpdateToLocation:fromLocation:
, Если ему более 60 секунд, не используйте его.