应用程序终止时,后台位置跟踪无法正常工作

时间:2014-03-13 11:38:34

标签: ios objective-c background location cllocation

我有一个应用程序,用于监控进入区域的情况。在进入时,该应用程序将通过本地通知提醒用户。

当应用启用或在后台运行时,此功能正常。但是,如果应用程序终止,则区域监视永远不会引发本地通知。

在info.plist中设置我的“后台模式”键。

这可能是因为我的CLLocation代码不在AppDelegate中(而是在单例中)吗?

这可能是因为无法运行代码来提升终止状态的位置通知吗?

这是输入区域时的代码:

- (void)locationManager:(CLLocationManager *)manager didEnterRegion:(CLRegion *)region {

    UIApplication* app = [UIApplication sharedApplication];
    UILocalNotification* notifyAlarm = [[UILocalNotification alloc] init];

    notifyAlarm.fireDate = [NSDate dateWithTimeIntervalSinceNow:5];;
    notifyAlarm.timeZone = [NSTimeZone defaultTimeZone];
    notifyAlarm.repeatInterval =NSDayCalendarUnit;
    notifyAlarm.alertBody = [Installation currentInstallation].reminderText;

    [app scheduleLocalNotification:notifyAlarm];
}

1 个答案:

答案 0 :(得分:0)

有两件事情发生: a)如果在更新发生时应用程序被暂停,系统会在后台将其唤醒以处理更新。

b)如果应用程序启动此服务然后终止,则系统会在新位置可用时自动重新启动应用程序。

我们现在可以做的是当用户点击主页键时打开重要的位置更新,我们可以让系统在需要时唤醒我们。

-(void) applicationDidEnterBackground:(UIApplication *) application
{

    // You will also want to check if the user would like background location
    // tracking and check that you are on a device that supports this feature.
    // Also you will want to see if location services are enabled at all.
    // All this code is stripped back to the bare bones to show the structure
    // of what is needed.

    [locationManager startMonitoringSignificantLocationChanges];
}

然后在应用程序启动时可能切换到更高的准确度,使用;

-(void) applicationDidBecomeActive:(UIApplication *) application
{

       [locationManager stopMonitoringSignificantLocationChanges];
       [locationManager startUpdatingLocation];
}

接下来,您可能希望更改位置管理员代理以处理后台位置更新。

-(void) locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation
{

    BOOL isInBackground = NO;
    if ([UIApplication sharedApplication].applicationState == UIApplicationStateBackground)
    {
        isInBackground = YES;
    }

    // Handle location updates as normal.

    if (isInBackground)
    {
        // Do, if you have to send location to server, or what you need
    }
    else
    {
        // ...
    }
}

请注意:后台位置监控将对电池使用产生影响。

此代码取自http://www.mindsizzlers.com/2011/07/ios-background-location/