2013-11-14 3 views
0

Я пытаюсь получить обновления местоположения, когда телефон заблокирован или работает в фоновом режиме, и я не могу заставить его работать.CLLocationManager не получает обновления фона в ios7

Вот что я сделал. Я добавил Required Background Modes 'location' в приложение plist и настроил диспетчер местоположений в следующем initMethod.

-(id)init { 
    if (self = [ super init ]) { 
     self.locationManager = [ CLLocationManager new ]; 
     self.locationManager.delegate = self; 
     self.locationManager.pausesLocationUpdatesAutomatically = NO; 
     //self.locationManager.distanceFilter = 75; 
     //self.locationManager.desiredAccuracy = 20; 
     self.currentSegment = [ [ BestRouteSegment alloc ] init ]; 
     self.segmentKeys = 
     [ [ NSArray alloc ] init ]; 
    } 

    return self; 
} 

я реализовал методы делегата и все работает отлично, пока приложение находится на переднем плане, но как только я прикасаюсь к экрану домашнего или заблокировать телефон обновление остановить. Я прочитал несколько сообщений по этому вопросу, и я добавил все, что упоминалось в документации, и до сих пор не повезло. Какие-либо предложения?

Вот где я начинаю запрашивающих обновления

/* Initiates a new trip by allocating a trip on the heap and begins 
    requesting location updates 
*/ 
- (void)insertNewObject:(id)sender { 
    self.deepSleepPreventer = [[SleepPreventer alloc] init]; 
    [self.deepSleepPreventer startPreventSleep]; 
    if (!_itemsToDisplay) { 
     _itemsToDisplay = [ [ NSMutableArray alloc ] init ]; 
    } 
    self.brain.currentTrip = [ [ BestRouteTrip alloc ] init ]; 
    self.brain.currentRoute.allTripsFromRoute = 
    [ self.brain.currentRoute addTrip:self.brain.currentTrip ]; 
    [ self.brain.locationManager startUpdatingLocation ]; 

#warning Bad UI technique 
    // Hide back and add button from user 
    self.navigationItem.hidesBackButton = YES; 
    self.navigationItem.rightBarButtonItem = nil; 
    self.navigationItem.title = @"Trip Active ..."; 
} 

Вот где места находятся в стадии обработки.

- (void)locationUpdate:(CLLocation *) newLocation { 
    CLLocationCoordinate2D location; 
    location.latitude = newLocation.coordinate.latitude; 
    location.longitude = newLocation.coordinate.longitude; 
    if (self.brain.currentTrip) { 
     if (!self.brain.currentTrip.timer.start && 
      self.brain.currentSegment.startCoord.latitude) { 
      if ([ self.brain isCoordinate:location WithinDistance:200 
           OfCoordinate:self.brain.currentSegment.startCoord ]) { 
       // Don't start timing until destination is selected 
       if (self.brain.currentSegment.endCoord.latitude) 
        [ self.brain.currentTrip.timer startTiming ]; 
      } 
     } 

     if (!self.brain.currentTrip.timer.end && self.brain.currentSegment.endCoord.latitude) { 
      // Has the user reached their location once ending coord has been selected 
      if ([ self.brain isCoordinate:location WithinDistance:200 
           OfCoordinate:self.brain.currentSegment.endCoord ]){ 
       [ self.brain.currentTrip .timer stopTiming ]; 
       self.brain.currentTrip.tripTime = 
       [ self.brain.currentTrip.timer elapsedTime ]/60.0; // Convert to minutes 
       [ self.brain.locationManager stopUpdatingLocation ]; 
       NSIndexPath *indexPath = 
       [ NSIndexPath indexPathForRow:_itemsToDisplay.count inSection:0 ]; 

       NSString *itemToDisplay = 
       [ @"Trip" stringByAppendingString: 
       [ NSString stringWithFormat:@"%d", _itemsToDisplay.count + 1 ] ]; 
       itemToDisplay = 
       [ itemToDisplay stringByAppendingString:[ NSString stringWithFormat:@" (%f)", self.brain.currentTrip.tripTime ] ]; 
       [ _itemsToDisplay insertObject:itemToDisplay atIndex: 
       _itemsToDisplay.count ]; 

       [ self.tableView insertRowsAtIndexPaths:@[indexPath] 
             withRowAnimation:UITableViewRowAnimationAutomatic ]; 
       self.brain.currentRoute.avgRouteTime = 
       [ self.brain.currentRoute determineAverageTime ]; 
       // Put buttons back on navigation bar 
       self.navigationItem.hidesBackButton = NO; 
       UIBarButtonItem *addButton = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemAdd target:self action:@selector(insertNewObject:)]; 
       self.navigationItem.rightBarButtonItem = addButton; 
       self.navigationItem.title = @"Trips"; 
       [ self.deepSleepPreventer stopPreventSleep ]; 
       [ self.brain writeData ]; 
      } 
     } 
    } 
} 
+0

Где вы запустить менеджер местоположения? –

+0

Я запускаю его внутри контроллера просмотра поездки, в методе insertNewObject. –

+0

Это единственное место, где вы его начинаете? Где вы его остановите? Возможно ли, что это прекращается, когда приложение помещается в фоновый режим? –

ответ

0

Для того, чтобы исправить эту проблему, я заменил Required Background Modes 'location' с Required Background modes 'App registers for location updates'

+0

Это то же самое, поэтому это не должно было иметь значения. (Вы можете переключаться между ними, щелкнув правой кнопкой мыши на записи в plist и (de), выбрав «Show Raw Keys/Values») –

+0

Это не одно и то же. Местоположение не является допустимой заменой. В ios7 вам нужно объявить его, как указано иначе, приложение не будет объявлено в настройках обновления фонового приложения телефона. –

+0

В итоге получается то же самое в plist –

Смежные вопросы