【问题标题】:Running a long process in the background in iOS5 and aboveiOS5及以上在后台运行长进程
【发布时间】:2013-03-26 04:50:23
【问题描述】:

我有一个使用 ASIHTTP 请求运行的下载队列。当用户按下主屏幕并且应用程序进入后台时,我希望此操作继续。我知道 ASIHTTP 请求可以在后台运行,但我希望运行 ASIHTTP 请求的进程也可以在后台运行。

我该怎么做?

我在 StackOverflow 看到了这个帖子:Continuing a long running process in the background under iOS4

但解决方案是在 iOS4 中。我想在 iOS5 及更高版本中执行此操作..

给出的解决方案:

UIApplication *app = [UIApplication sharedApplication];
if ([app respondsToSelector:@selector(beginBackgroundTaskWithExpirationHandler:)]) {
    backgroundTaskIdentifier = [[UIApplication sharedApplication] beginBackgroundTaskWithExpirationHandler:^{
        dispatch_async(dispatch_get_main_queue(), ^{
            if (backgroundTaskIdentifier != UIBackgroundTaskInvalid)
            {
                // you took too long - clean up what you can, then …
                [app endBackgroundTask:backgroundTaskIdentifier];
                backgroundTaskIdentifier = UIBackgroundTaskInvalid;
            }
        });
    }];
}

另一个问题是我应该把这段代码放在哪里。

在这方面需要一些指导..

【问题讨论】:

    标签: ios ios5 ios6 background-process


    【解决方案1】:

    您在另一个答案中找到的解决方案适用于 iOS 4.0 及更高版本。它工作得很好,并且在移动到后台时保持the recommended way 执行扩展任务。

    此外,除非您尝试支持 iOS 3.x(这已不再那么可取),否则您不需要 respondsToSelector 检查。

    【讨论】:

    • 它给了我一个错误:“指针和整数之间的比较”这一行:backgroundTaskIdentifier != UIBackgroundTaskInvalid
    • backgroundTaskIdentifier 不应该被声明为指针,或者您应该确保取消引用它以进行比较。有关详细信息,请参阅前面链接的编程指南、UIApplication 文档或链接到的 Apple 示例代码。
    猜你喜欢
    • 1970-01-01
    • 2013-11-23
    • 2023-03-10
    • 2021-04-06
    • 2016-11-17
    • 2012-10-05
    • 2013-02-04
    • 1970-01-01
    相关资源
    最近更新 更多