【发布时间】:2016-08-16 08:10:27
【问题描述】:
还有一个关于在后台运行 GPS 的问题。显然,在某些特定条件下,我的应用程序可以在后台运行(似乎无限期地),有时它会在 3 分钟后终止。我的 iPad 目前在 9.3.2 上运行。
TL;DR:进行了必要的代码和项目配置,但并不总是在后台运行超过 3 分钟。为什么?
我的帖子会很长。我试图保持简洁。
我的应用需要每隔一段时间发送一次 GPS 位置:如果用户“登录”,则需要 60 秒;如果用户“退出”,则需要 900 秒(15 分钟)。我需要这些要求; 课程要求不是我决定的。此应用也未发布到应用商店。
我知道我需要在我的 plist 中添加这个:
<key>NSLocationAlwaysUsageDescription</key>
<string>Location information from this device is required for tracking purposes.</string>
在项目功能下,我选择了背景模式 -> 位置更新,也在 plist 中:
<key>UIBackgroundModes</key>
<array>
<string>location</string>
</array>
在我的AppDelegate,我也有这两个(位于application:didFinishLaunchingWithOptions:里面):
if ([locationManager respondsToSelector:@selector(requestAlwaysAuthorization)])
{
[locationManager requestAlwaysAuthorization];
NSLog(@"===>locationManager responds to requestAlwaysAuthorization<===");
}
else
{
NSLog(@"===>locationManager not responding to requestAlwaysAuthorization! :(<===");
}
if([locationManager respondsToSelector:@selector(setAllowsBackgroundLocationUpdates:)])
{
[locationManager setAllowsBackgroundLocationUpdates:YES];
NSLog(@"===>locationManager responds to setAllowsBackgroundLocationUpdates<===");
}
else
{
NSLog(@"===>locationManager not responding to setAllowsBackgroundLocationUpdates! :(<===");
}
在我的applicationDidEnterBackground 中,我的beginBackgroundTaskWithExpirationHandler 函数如下:
bgTask = [[UIApplication sharedApplication] beginBackgroundTaskWithExpirationHandler:^{
NSLog(@"ending background task. Background time remaining: %f", [[UIApplication sharedApplication] backgroundTimeRemaining]);
//Do I need to uncomment the 2 lines below?
//[[UIApplication sharedApplication] endBackgroundTask:bgTask];
//bgTask = UIBackgroundTaskInvalid;
}];
所以现在,我最大的问题是:我还没有做/做错什么,不允许后台执行?
- 我的应用程序有一个 csv 日志文件(本地),该文件记录了发送到跟踪 Web 服务的 GPS 坐标。在我的日志中,我还记录了“应用程序到后台”和“应用程序到前台”等事件,所以当我检索日志时,我会知道它是否在 3 分钟后终止。另外,我记录了
[[UIApplication sharedApplication] backgroundTimeRemaining]的剩余时间。 - 我有
CLLocationManager *locationManager;。当我的应用程序进入后台时,我会创建[locationManager setDesiredAccuracy:kCLLocationAccuracyThreeKilometers];然后[locationManager startUpdatingLocation];只是为了让应用程序在后台运行。计时器在上述间隔时更改[locationManager setDesiredAccuracy:kCLLocationAccuracyBest];,然后将其更改回[locationManager setDesiredAccuracy:kCLLocationAccuracyThreeKilometers]。所有这些都是当应用程序在后台时,[locationManager stopUpdatingLocation];仅当应用程序在前台时。我是否真的需要让 locationManager 保持运行,以便应用在后台保持活动状态? -
奇怪的部分如下:我意识到当我通过以下方式将我的应用程序发送到后台时:(a.)主页按钮(b.)电源按钮(c.)关闭 iPad 外壳,(a.)将始终让应用程序在后台运行,而 (b.) 和 (c.) 可能 允许应用程序运行超过 3 分钟 ??!?真的有区别吗?因为我知道委托函数它是否运行超过 3 分钟似乎是不确定的。applicationWillResignActive和applicationDidEnterBackground仍然会被调用。 - 我是否将
beginBackgroundTaskWithExpirationHandler放在了正确的位置? - 我是否将
[locationManager setAllowsBackgroundLocationUpdates:YES];放在了正确的位置(当前在 AppDelegaate 中)? - 使用 xcode 调试器运行应用程序将始终完美运行,但不使用(即实际使用条件)运行它可能无法让应用程序运行。随着调试器的运行,我 NSLog 剩余的后台时间。它可能会显示类似 179.348015 秒的内容,但 3 分钟后应用程序将继续运行。其他人也面临这个问题吗?
非常感谢您的帮助。 o/
【问题讨论】:
标签: ios objective-c timer background gps