设备锁定时,重要位置更改未正确触发

时间:2015-02-23 20:20:50

标签: ios location core-location

我试图找出当设备被锁定时使用重要位置更改时未触发locationManager:didUpdateLocations:的原因。

到目前为止locationManager:didUpdateLocations:只有在按下主页按钮唤醒设备后才会触发新位置

我使用的是iOS 8.1,但不知道这是否是正常行为。

这是我的代码(AppDelegate.m):

    - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
        if ([launchOptions objectForKey:UIApplicationLaunchOptionsLocationKey]){
            NSLog(@"LAUNCHED BY LOCATION UPDATE");
        }
        [self startLocationTrack];
    }

        -(void)startLocationTrack
    {
        if (_locationManager == nil) {
            _locationManager = [[CLLocationManager alloc] init];
            _locationManager.delegate = self;
            _locationManager.pausesLocationUpdatesAutomatically = NO;
            _locationManager.activityType = CLActivityTypeAutomotiveNavigation;
            _locationManager.desiredAccuracy = kCLLocationAccuracyBestForNavigation;
            if ([_locationManager respondsToSelector:@selector(requestAlwaysAuthorization)]) {
                [_locationManager requestAlwaysAuthorization];
            }
            [_locationManager startMonitoringSignificantLocationChanges];
        }else{
            [_locationManager startMonitoringSignificantLocationChanges];
        }
    }

    - (void)locationManager:(CLLocationManager *)manager
         didUpdateLocations:(NSArray *)location
    {    

        UILocalNotification *notification = [[UILocalNotification alloc] init];
        [notification setFireDate:[NSDate dateWithTimeIntervalSinceNow:5]];
        notification.timeZone = [NSTimeZone defaultTimeZone];
        [notification setSoundName:UILocalNotificationDefaultSoundName];
        notification.alertBody = @"YOU HAVE MOVE A SIGNIFICANT DISTANCE!!";
        notification.alertAction = NSLocalizedString(@"Read Msg", @"Read Msg");
        notification.applicationIconBadgeNumber=0;
        notification.repeatInterval=0;
        [[UIApplication sharedApplication] scheduleLocalNotification:notification];
    }

1 个答案:

答案 0 :(得分:1)

首先,我认为您可能无法开始跟踪应用程序是否已启动,而在其他地方,当应用程序已启动时,您可以检查您的应用是否已获得授权

if ([CLLocationManager authorizationStatus] == kCLAuthorizationStatusNotDetermined)
    [locationManager requestAlwaysAuthorization];

你的代表应该等待这个

- (void)locationManager:(CLLocationManager *)manager didChangeAuthorizationStatus:(CLAuthorizationStatus)status
{
    if (status == kCLAuthorizationStatusAuthorizedAlways) {
        [locationManager startMonitoringSignificantLocationChanges];
    }
}

您还需要将NSLocationAlwaysUsageDescription添加到您的Info.plist文件中,否则将永远不会提示用户授权您的应用,一旦您的应用获得授权,您就可以开始跟踪该设备

我必须提到locationManager在其他地方,而不是作为AppDelegate中的属性,我使用了静态var,可以使用单例访问,但是你可能有另一种访问方式