设备锁定时,重大位置更改无法正确触发

3

我正在研究为什么在设备锁定时使用“重大位置更改”时,locationManager:didUpdateLocations:没有被触发。

到目前为止,locationManager:didUpdateLocations:仅在通过按Home按钮唤醒设备后才会触发新位置的更新。

我正在使用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
首先,我认为您可能不应该在应用程序启动时开始跟踪,而是在其他地方,在应用程序已经启动时,您可以检查您的应用程序是否已被授权。
if ([CLLocationManager authorizationStatus] == kCLAuthorizationStatusNotDetermined)
    [locationManager requestAlwaysAuthorization];

而你的代理应该等待这个

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

你需要在 Info.plist 文件中添加 NSLocationAlwaysUsageDescription,否则用户将永远不会被提示授权你的应用程序。一旦你的应用程序被授权,你就可以开始跟踪设备了。

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


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接