gpt4 book ai didi

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

转载 作者:IT王子 更新时间:2023-10-29 08:10:37 26 4
gpt4 key购买 nike

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

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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com