OGeek|极客世界-中国程序员成长平台

标题: ios - AFNetworking后台下载一段时间后自动停止,我需要恢复它 [打印本页]

作者: 菜鸟教程小白    时间: 2022-12-12 15:41
标题: ios - AFNetworking后台下载一段时间后自动停止,我需要恢复它

我正在使用 AFNetwork(它基于 NAFDownloadRequestOperation),我的任务是从亚马逊存储桶中一一下载多个 zip 文件。 当应用程序处于前台时,一切都运行良好,但是当应用程序进入后台模式时,时间下载只运行一段时间,它会自动停止。我读了一些关于它的博客,因为我在下载停止之前调用了以下方法。

 [self.operationUpdate setShouldExecuteAsBackgroundTaskWithExpirationHandler:^{
                NSLog(@"downloading will stop");
            }];

我也在 AppDelegate 中使用了以下代码,但我不明白如何恢复之前的下载。

__block UIBackgroundTaskIdentifier backgroundTaskIdentifier = [application beginBackgroundTaskWithExpirationHandler:^(void) {
        [application endBackgroundTask:backgroundTaskIdentifier];
        NSLog(@"applicationWillResignActive");

        [__SERVER_INSTANCE cancellAllDownloading];

     //   [[YourRestClient sharedClient] cancelAllHTTPOperations];
    }];

如果有人有任何解决方案,请告诉我,提前谢谢。



Best Answer-推荐答案


您应该使用 AFDownloadRequestOperation

您的请求将如下所示

AFDownloadRequestOperation *operation = [[AFDownloadRequestOperation alloc] initWithRequest:request targetPath:path shouldResume:YES];
    [operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
        NSLog(@"Successfully downloaded file to %@", path);
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        NSLog(@"Error: %@", error);
    }];
    [operations addObjectperation];

重新启动应用程序并生成具有相同 url 的请求后,它将继续下载。 "shouldResume:YES"有效。

因此,您可以在后台任务中重新创建完成下载的请求

__block UIBackgroundTaskIdentifier backgroundTaskIdentifier = [application beginBackgroundTaskWithExpirationHandler:^(void) {
        [application endBackgroundTask:backgroundTaskIdentifier];
        NSLog(@"applicationWillResignActive");

        [__SERVER_INSTANCE cancellAllDownloading];

     //   recreate here your request to finish fownload, 
     //or recreate in when app will enter foreground
    }];

希望对你有帮助

关于ios - AFNetworking后台下载一段时间后自动停止,我需要恢复它,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31176421/






欢迎光临 OGeek|极客世界-中国程序员成长平台 (http://ogeek.cn/) Powered by Discuz! X3.4