如果用户在应用处于后台模式时进入或退出某个区域,我需要执行调用localNoification的简单任务。只有一组坐标会触发通知。例如:
Lat:41.8500 Lon:87.6500 半径:300
我知道如何调用localNotification,以及如何使用locationManager的基本功能,但似乎无法跟踪后台的位置。任何帮助都会很棒!
答案 0 :(得分:3)
您是否了解过CLLocationManager的startMonitoringForRegion:
方法?我认为这将完全符合您的要求。设置它的代码看起来像这样:
CLRegion * region = [[CLRegion alloc] initCircularRegionWithCenter: CLLocationCoordinate2DMake(41.8500, 87.6500) radius: 300 identifier: @"regionIDstring"];
CLLocationManager * manager = [[CLLocationManager alloc] init];
[manager setDelegate: myLocationManagerDelegate];
[manager startMonitoringForRegion: region];
之后,即使您的应用处于后台,设备也会监控指定区域的入口/出口。越过某个地区后,代表将接到来电locationManager:didEnterRegion:
或locationManager:didExitRegion:
。您可以借此机会发布UILocalNotification
。如果您的应用在跨区域时未运行,则会在后台启动,您需要在application: didFinishLaunchingWithOptions:
中查找相应的密钥。使用如下代码:
if ([launchOptions objectForKey: UIApplicationLaunchOptionsLocationKey] != nil) {
// create a location manager, and set its delegate here
// the delegate will then receive the appropriate callback
}
请注意,应用程序在后台运行时只需要很短的时间(几秒钟);如果您需要执行更长的任务,请在应用程序收到区域通过通知后立即调用Nebs在其答案中提及的beginBackgroundTaskWithExpirationHandler:
方法。这将使您在后台运行大约600秒。
答案 1 :(得分:2)
查看UIApplication
的beginBackgroundTaskWithExpirationHandler:
方法。它允许您在应用程序处于后台时请求额外的时间来运行任务。
有关详情,建议您阅读iOS app programming guide的“后台执行和多任务”部分。它详细解释了当应用程序进入后台时会发生什么以及您可以做什么。
具体来说,它显示了当应用程序进入后台时运行长任务的示例代码:
[此代码取自上面链接的Apple指南]
- (void)applicationDidEnterBackground:(UIApplication *)application
{
bgTask = [application beginBackgroundTaskWithExpirationHandler:^{
// Clean up any unfinished task business by marking where you.
// stopped or ending the task outright.
[application endBackgroundTask:bgTask];
bgTask = UIBackgroundTaskInvalid;
}];
// Start the long-running task and return immediately.
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
// Do the work associated with the task, preferably in chunks.
[application endBackgroundTask:bgTask];
bgTask = UIBackgroundTaskInvalid;
});
}