在 iOS 5 中,当 Application Enter 后台 wi-fi 连接丢失。
但是我想在设备休眠前的接下来的 4-5 分钟内使用 wi-fi 连接,因为某些任务可以在应用程序进入后台的 4-5 分钟内执行。
我认为这可以通过使用来完成beginBackgroundTaskWithExpirationHandler:
,但我无法解决问题
我处理这个问题的方法是beginBackgroundTaskWithExpirationHandler
用于我发送的每个网络请求。
这样,即使我的应用程序移至后台,我也可以确保我的所有网络都将完成。
我通常使用一个单例对象来处理所有网络请求,所以在发送请求之前我调用
- (void)startBackgroundTask
{
// ask for extra time if this is called when app go to suspended
UIApplication *application = [UIApplication sharedApplication];
_bgTask = [application beginBackgroundTaskWithExpirationHandler:^{
// Clean up any unfinished task business by marking where you.
// stopped or ending the task outright.
[application endBackgroundTask:_bgTask];
_bgTask = UIBackgroundTaskInvalid;
}];
}
在我得到响应(成功/失败)或者如果我取消请求后,我会打电话
- (void)stopBackgroudTask
{
UIApplication *app = [UIApplication sharedApplication];
if (_bgTask != UIBackgroundTaskInvalid) {
[app endBackgroundTask:_bgTask];
_bgTask = UIBackgroundTaskInvalid;
}
}
* 不要忘记定义UIBackgroundTaskIdentifier *_bgTask;
此外,如果您打算大量使用 Wi-Fi,则应将Application uses Wi-Fi
plist 文件中的密钥设置为 YES,否则即使您的应用程序正在运行,您的 Wi-Fi 也会在 30 分钟后关闭。
只需禁用 iPhone 即可进入睡眠模式
-(void) sleepModeDisable{
[[UIApplication sharedApplication] setIdleTimerDisabled:NO];
[[UIApplication sharedApplication] setIdleTimerDisabled:YES];
}
每 10 秒调用一次这个函数,这可能对你有帮助
这里没有火箭科学,这是 iOS 中的预期行为,即在手机锁定时 Wi-Fi 会在手机锁定时关闭,除非你告诉 iOS 你的应用程序需要持久 Wi-Fi,然后当你的应用程序运行时它不会为你关闭它跑步。
为此,只需添加UIRequiresPersistentWiFi
到您的 info.plist 并标记它YES