2012-04-06 7 views
2

Im собирает приложение, которое выдает уведомление, когда пользователь покидает дом. Таким образом, я реализовал мониторинг области с радиусом 25. Проблема, с которой я сталкиваюсь, заключается в моделировании (iPhone simulator 5.0), я установил пользовательское местоположение (home), задающее границу области. затем введите другое пользовательское местоположение за пределами границы области i.e в конце улицы. Но приложение не регистрирует выход из региона. Только после того, как я установил исходное местоположение и регион, затем перейдите в штаб-квартиру Apple, зарегистрируйте и запустите уведомление. Приложение переключается на значительное изменение местоположения в фоновом режиме. Но у него такая же проблема, как на переднем плане, так и на заднем плане. Что нужно искать, например, приложение «Напоминания», для приложения, чтобы запустить уведомление очень скоро после выхода/выхода из границы области, идя до конца улицы. Как сделать его более точным?Как улучшить точность пересечения границ региона (симуляция) (geofencing)

вот некоторые из моего файла viewcontroller.m:

- (void)viewDidLoad { 
    [super viewDidLoad]; 

    // Create empty array to add region events to. 
    updateEvents = [[NSMutableArray alloc] initWithCapacity:0]; 

    // Create location manager with filters set for battery efficiency. 
    locationManager = [[CLLocationManager alloc] init]; 
    locationManager.delegate = self; 
    locationManager.distanceFilter = kCLLocationAccuracyBest; //could try KLDistanceFilterNone; 
    locationManager.desiredAccuracy = kCLLocationAccuracyBest; 

    // Start updating location changes. 
      [locationManager startUpdatingLocation]; 
} 

- (void)viewDidAppear:(BOOL)animated { 
    // Get all regions being monitored for this application. 
    NSArray *regions = [[locationManager monitoredRegions] allObjects]; 

    // Iterate through the regions and add annotations to the map for each of them. 
      for (int i = 0; i < [regions count]; i++) { 
        CLRegion *region = [regions objectAtIndex:i]; 
    RegionAnnotation *annotation = [[RegionAnnotation alloc] initWithCLRegion:region]; 
        [regionsMapView addAnnotation:annotation]; 
        [annotation release]; 
      } 
} 

- (void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error { 
    NSLog(@"didFailWithError: %@", error); 
} 


- (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation { 
    NSLog(@"didUpdateToLocation %@ from %@", newLocation, oldLocation); 

    // Work around a bug in MapKit where user location is not initially zoomed to. 
      if (oldLocation == nil) { 
    // Zoom to the current user location. 
        MKCoordinateRegion userLocation = MKCoordinateRegionMakeWithDistance(newLocation.coordinate, 100.0, 100.0); 
        [regionsMapView setRegion:userLocation animated:YES]; 
      } 
} 


- (void)locationManager:(CLLocationManager *)manager didEnterRegion:(CLRegion *)region { 
    NSString *event = [NSString stringWithFormat:@"didEnterRegion %@ at %@", region.identifier, [NSDate date]]; 

      [self updateWithEvent:event]; 
} 


- (void)locationManager:(CLLocationManager *)manager didExitRegion:(CLRegion *)region { 
    NSString *event = [NSString stringWithFormat:@"didExitRegion %@ at %@", region.identifier, [NSDate date]]; 
      [self updateWithEvent:event]; 
//implement local notification: 
    UIApplication *app    = [UIApplication sharedApplication]; 
    UILocalNotification *notification = [[UILocalNotification alloc] init]; 
    [[UIApplication sharedApplication] cancelAllLocalNotifications]; 

    if (notification == nil) 
     return; 
    notification.alertBody = [NSString stringWithFormat:@"Did You Lock Your House?"]; 
    notification.alertAction = @"Lock House"; 
    notification.soundName = UILocalNotificationDefaultSoundName; 
    notification.applicationIconBadgeNumber = 1; 
    [app presentLocalNotificationNow:notification]; 

    [notification release]; 
// ends here 

//following is an alert for the case of exiting boundary whilst app is in foreground 
    UIAlertView *alr=[[UIAlertView alloc] initWithTitle:@"Reminder didExitRegion" message:region.identifier delegate:nil cancelButtonTitle:nil otherButtonTitles:@"Ok",nil]; 

    [alr show]; 

    [alr release]; 
    //ends here 
} 

- (void)locationManager:(CLLocationManager *)manager monitoringDidFailForRegion:(CLRegion *)region withError:(NSError *)error { 
    NSString *event = [NSString stringWithFormat:@"monitoringDidFailForRegion %@: %@", region.identifier, error]; 

      [self updateWithEvent:event]; 
} 

- (IBAction)addRegion { 
    if ([CLLocationManager regionMonitoringAvailable]) { 
    // Create a new region based on the center of the map view. 
    CLLocationCoordinate2D coord = CLLocationCoordinate2DMake(regionsMapView.centerCoordinate.latitude, regionsMapView.centerCoordinate.longitude); 
    CLRegion *newRegion = [[CLRegion alloc] initCircularRegionWithCenter:coord 
                                               radius:25.0 
                                            identifier:[NSString stringWithFormat:@"%f, %f", regionsMapView.centerCoordinate.latitude, regionsMapView.centerCoordinate.longitude]]; 

    // Create an annotation to show where the region is located on the map. 
        RegionAnnotation *myRegionAnnotation = [[RegionAnnotation alloc] initWithCLRegion:newRegion]; 
        myRegionAnnotation.coordinate = newRegion.center; 
        myRegionAnnotation.radius = newRegion.radius; 

        [regionsMapView addAnnotation:myRegionAnnotation]; 

        [myRegionAnnotation release]; 

    // Start monitoring the newly created region. 
        [locationManager startMonitoringForRegion:newRegion desiredAccuracy:kCLLocationAccuracyBest]; 

        [newRegion release]; 
      } 
    else { 
    NSLog(@"Region monitoring is not available."); 
      } 
} 

Эта работа была получена из «регионов» шаблон.

+0

Ive развернул приложение на своем iPhone, установил область между 15-25 м и прошел хороший 50 м за пределами региона и ничего. любые рекомендации? –

ответ

1

Это о лучшей точности, которую вы получите. В области соответствия используется только триангуляция ячейки башни, поэтому в плотных областях она может срабатывать при 50-100 м, а в редких областях - 100 м.

Если вы хотите получить более тонкие детали, тогда вы сможете использовать услуги прямого определения местоположения. Но это будет есть батарея, поэтому заберите свой яд.

6

iOS симулятор, как известно, плохо для обновлений geofence с выходом/enter. Один из способов, с помощью которого вы можете установить это, - это настроить геозонность вашего приложения как своего текущего местоположения. Затем из отладочного меню iOS-симулятора, нажмите местоположение, а затем Freeway Drive. Теперь ваше устройство будет симулировать движение по автостраде, и если ваш симулятор будет похож на мой, он не зарегистрирует событие didExitRegion.

Почему? Регионы в основном определяются скрытым алгоритмом Apple, использующим Wi-Fi, сотовые башни и другие приложения на запрашивающем телефон адресе. Увидев, что в качестве симулятора не используются Wi-Fi или сотовые вышки ... Мониторинг области будет довольно невозможным.

Чтобы проверить, работает ли остальная часть вашего кода после выхода из региона, вы можете создать кнопку или что-то, что вручную запускает ваше locationManager: didExitRegion: method. Я также настоятельно рекомендую компилировать проект на вашем устройстве, подключив его и перейдя с iPhone Simulator на ваше устройство iOS. Затем вы можете отключить свое устройство и запустить приложение со своего телефона, чтобы проверить его.