2015-07-10 2 views
4

Я работаю над прототипом, чтобы уведомить пользователя о значительном изменении местоположения. Когда приложение закрыто/завершено, я отправляю локальное уведомление, чтобы уведомить пользователя. Уведомление работает отлично, но, для один раз только. Хотя я получил изменение местоположения в didFinishLaunching:, я не получаю локальное уведомление. Ниже мой простой код.Локальное уведомление о существенном изменении местоположения

В ViewController Я регистрирую уведомление.

#import "LocationViewController.h" 

@interface LocationViewController() 

@end 

@implementation LocationViewController 

- (void)viewDidLoad 
{ 
    [super viewDidLoad]; 
    // Do any additional setup after loading the view, typically from a nib. 

    // Registerimg for Motification 
    if ([[UIApplication sharedApplication] respondsToSelector:@selector(registerUserNotificationSettings:)]) { 
     UIUserNotificationSettings* notificationSettings = [UIUserNotificationSettings settingsForTypes:UIUserNotificationTypeAlert | UIUserNotificationTypeBadge | UIUserNotificationTypeSound categories:nil]; 
     [[UIApplication sharedApplication] registerUserNotificationSettings:notificationSettings]; 
     [[UIApplication sharedApplication] registerForRemoteNotifications]; 
    } else { 
     [[UIApplication sharedApplication] registerForRemoteNotificationTypes: (UIRemoteNotificationTypeBadge | UIRemoteNotificationTypeSound | UIRemoteNotificationTypeAlert)]; 
    } 
} 

Ниже мой didFinishLaunching:

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions 
{ 
    NSLog(@"didFinishLaunchingWithOptions"); 

    self.shareModel = [LocationShareModel sharedModel]; 
    self.shareModel.afterResume = NO; 

    [self addApplicationStatusToPList:@"didFinishLaunchingWithOptions"]; 

    UIAlertView * alert; 

    //We have to make sure that the Background App Refresh is enable for the Location updates to work in the background. 
    if([[UIApplication sharedApplication] backgroundRefreshStatus] == UIBackgroundRefreshStatusDenied){ 

     alert = [[UIAlertView alloc]initWithTitle:@"" 
              message:@"The app doesn't work without the Background App Refresh enabled. To turn it on, go to Settings > General > Background App Refresh" 
             delegate:nil 
           cancelButtonTitle:@"Ok" 
           otherButtonTitles:nil, nil]; 
     [alert show]; 

    }else if([[UIApplication sharedApplication] backgroundRefreshStatus] == UIBackgroundRefreshStatusRestricted){ 

     alert = [[UIAlertView alloc]initWithTitle:@"" 
              message:@"The functions of this app are limited because the Background App Refresh is disable." 
             delegate:nil 
           cancelButtonTitle:@"Ok" 
           otherButtonTitles:nil, nil]; 
     [alert show]; 

    } else{ 

     // When there is a significant changes of the location, 
     // The key UIApplicationLaunchOptionsLocationKey will be returned from didFinishLaunchingWithOptions 
     // When the app is receiving the key, it must reinitiate the locationManager and get 
     // the latest location updates 

     // This UIApplicationLaunchOptionsLocationKey key enables the location update even when 
     // the app has been killed/terminated (Not in th background) by iOS or the user. 

     if ([launchOptions objectForKey:UIApplicationLaunchOptionsLocationKey]) { 
      NSLog(@"UIApplicationLaunchOptionsLocationKey"); 

      [[UIApplication sharedApplication] cancelAllLocalNotifications]; 

      //Establish notification details 
      UILocalNotification *notification = [[UILocalNotification alloc] init]; 
      notification.fireDate = [NSDate date]; 
      notification.timeZone = [NSTimeZone defaultTimeZone]; 
      notification.repeatInterval = 0; 
      notification.alertBody = [NSString stringWithFormat:@"Success"]; 
      notification.soundName = UILocalNotificationDefaultSoundName; 
      [[UIApplication sharedApplication] scheduleLocalNotification:notification]; 
      [[UIApplication sharedApplication] presentLocalNotificationNow:notification]; 

      // This "afterResume" flag is just to show that he receiving location updates 
      // are actually from the key "UIApplicationLaunchOptionsLocationKey" 
      self.shareModel.afterResume = YES; 

      self.shareModel.anotherLocationManager = [[CLLocationManager alloc]init]; 
      self.shareModel.anotherLocationManager.delegate = self; 
      self.shareModel.anotherLocationManager.desiredAccuracy = kCLLocationAccuracyBestForNavigation; 
      self.shareModel.anotherLocationManager.activityType = CLActivityTypeOtherNavigation; 

      if(IS_OS_8_OR_LATER) { 
       [self.shareModel.anotherLocationManager requestAlwaysAuthorization]; 
      } 

      [self.shareModel.anotherLocationManager startMonitoringSignificantLocationChanges]; 

      [self addResumeLocationToPList]; 
     } 
    } 

    return YES; 
} 

Я следую this учебник для изменения местоположения и добавил мои методы уведомления к нему.

Где я могу получить уведомление о каждом существенном изменении местоположения?

ответ

0

Я получил ответ сам после некоторого расследования.

Когда приложение прослушивает значительное изменение местоположения, и если приложение закрыто, при изменении местоположения вызывается didFinishLaunchingWithOptions:, и я получаю локальное уведомление, как обсуждалось в моем вопросе.

Это означает, что приложение запущено, но не на переднем плане.

Для следующего изменения местоположения didFinishLaunchingWithOptions: не будет вызван, так как приложение уже запущено. Таким образом, общий метод делегирования, CLLocationManagerDelegate, didUpdateLocations: получит звонок для всех изменений местоположения там после.

0

Я полагаю, что вы используете iOS 8 или выше в качестве цели развертывания. Вы добавили NSLocationWhenInUseUsageDescription в вас info.plist? Я не вижу этого в вашем учебнике, и это обязательно для локальных библиотек.

+0

Я добавил requestAlwaysAuthorization в коде и NSLocationAlwaysUsageDescription в plist также. – iOS

+0

Попытайтесь использовать диспетчер LocationManager и посмотрите, получили ли вы местоположение вашей текущей позиции. – Ricardo

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