ios - 在前台使用 NSURLConnection 启动的连接如何在后台继续?

标签 ios

我已经搜索了数周,试图找到答案或如何执行此操作的示例。

NSURLConnection 的所有示例/教程都显示它从前台开始或从后台开始,同上 beginBackgrounTaskWithExpirationHandler 的所有示例:显示如何在进入后台后启动后台任务。

据我所知,互联网或书籍上没有任何内容可以说明如何在前台启动连接,如果未完成则在后台继续连接。

这个问题的答案实际上并没有回答问题:

How should beginbackgroundtaskwithexpirationhandler: be dealt with for an NSUrlConnection that is already in progress?

如果您阅读了引用的 Beyond The Basics 部分,它会说:“当应用程序在前台时,后台任务不会产生任何影响”。这意味着如果您想在前台下载,则无法在前台使用 NSURLConnection 启动后台任务。

最佳答案

您只需调用 beginBackgroundTaskWithExpirationHandler: 当您开始下载过程时您的应用程序就在前台。请注意,您必须将返回值存储在 ivar/property 中:

@property (nonatomic, assign) UIBackgroundTaskIdentifier backgroundTaskID;

@synthesize backgroundTaskID;

...

NSURLConnection *connection = [NSURLConnection connectionWithRequest:request delegate:self];
self.backgroundTaskID = [[UIApplication sharedApplication] beginBackgroundTaskWithExpirationHandler:^{
    // Cancel the connection
    [connection cancel];
}];

这将使您的应用程序在下载运行时被发送到后台时继续运行。然后,在表示下载完成的委托(delegate)方法中,您必须放置匹配的 endBackgroundTask::

- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
    // Handle the error
    ...

    [[UIApplication sharedApplication] endBackgroundTask:self.backgroundTaskID];
}

- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
    // Save the downloaded data
    ...

    [[UIApplication sharedApplication] endBackgroundTask:self.backgroundTaskID];
}

关于ios - 在前台使用 NSURLConnection 启动的连接如何在后台继续?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9163960/

相关文章:

ios - Mapbox 标注配件

ios - 通过 iPhone IOS 测试 React Native

ios - Facebook ID 字符串长度

ios - 我们可以只向部分用户发布 iOS 应用程序的更新吗?

ios swift - 以编程方式更新约束

ios - 无法在 Xcode 11 的 Storyboard 中设置 UIView 的比例高度

ios - iOS 中的 Stripe Connect 支付

ios - Xcode iOS 使用 git

ios - 使用自动布局调整 UIImage 的纵横比

ios - FetchedResults Controller 过滤计算值