如何实现 UIRequiresPersistentWifi 以在后台运行应用程序
How to implement UIRequiresPersistentWifi to work application in the background
我的应用程序需要在后台持续连接 wifi,我认为唯一的方法是将 UIRequiresPersistentWifi
应用到 info.plist 文件。因此,下面是我添加到 info.plist、
的内容
我用 YES
添加了 UIRequiresPersistentWifi
。
我添加了 Required device capabilities
和 wifi
我在代码中创建了 NSInputStream
、NSOutputStream
流。即使在完成所有这些套接字之后也无法在后台工作。我还缺少什么?
我应该向 - (void)applicationDidEnterBackground:(UIApplication *)application
委托方法添加任何代码吗?
是的,我们必须在 applicationDidEnterBackground
中添加代码,如下所示。
- (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.
bgTask = UIBackgroundTaskInvalid;
});
}
我的应用程序需要在后台持续连接 wifi,我认为唯一的方法是将 UIRequiresPersistentWifi
应用到 info.plist 文件。因此,下面是我添加到 info.plist、
我用 YES
添加了 UIRequiresPersistentWifi
。
我添加了 Required device capabilities
和 wifi
我在代码中创建了 NSInputStream
、NSOutputStream
流。即使在完成所有这些套接字之后也无法在后台工作。我还缺少什么?
我应该向 - (void)applicationDidEnterBackground:(UIApplication *)application
委托方法添加任何代码吗?
是的,我们必须在 applicationDidEnterBackground
中添加代码,如下所示。
- (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.
bgTask = UIBackgroundTaskInvalid;
});
}