如何继续下载新的图像在后台,即使用户强制退出应用程序在iOS目标C?

我想在300左右下载许多图像,并将其显示在UI中。

我有两个问题:

  1. 如果应用程序在前台,并假设用户将其发送到后台模式(通过单击主页button),那么如何确保下载继续?

  2. 如果用户强制退出应用程序(双击主屏幕button并从应用程序切换器上轻扫应用程序),那么如何确保应用程序下载图像?

我一直在阅读关于背景的东西。 很less有人说在2.情况下下载不能继续。

以下是我提到的链接:

http://www.appcoda.com/ios7-background-fetch-programming/ http://www.appcoda.com/background-transfer-service-ios7/ iOS后台下载应用程序不活动

我没有得到正确的方法来下载图像在前台,背景/暂停,用户强制退出应用程序。 我正在使用AFNetworking进行web服务调用。

以下是我的代码:

我有图像的细节,如.json文件中的url上传到亚马逊。 要下载我所做的文件,

[NSData dataWithContentsOfURL:[NSURL URLWithString:@"https://someurl/imageFile.json"]]; 

从这个文件我读了图像的url,并下载他们的图像细节。 这是一个很大的过程。 我如何处理? 请帮忙..

您的1个问题的解决scheme如下:

后台会话允许您在应用程序未运行时在后台执行上传和下载内容。 您可以通过调用NSURLSessionConfiguration类的backgroundSessionConfiguration:方法来创build后台会话configuration。

 NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:URL]; NSURLSessionConfiguration *sessionConfig; float timeout = 5 * 60.0f; BOOL iOS8OrNew = [[[UIDevice currentDevice] systemVersion] floatValue] >= 8.0; if (iOS8OrNew) { sessionConfig = [NSURLSessionConfiguration backgroundSessionConfigurationWithIdentifier:identifier]; request.timeoutInterval = timeout; } else { sessionConfig = [NSURLSessionConfiguration backgroundSessionConfiguration:identifier]; sessionConfig.timeoutIntervalForRequest = timeout; } sessionConfig.HTTPMaximumConnectionsPerHost = 10; AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:sessionConfig]; NSURLSessionDownloadTask *downloadTask = [manager downloadTaskWithRequest:request]; [manager setDidFinishEventsForBackgroundURLSessionBlock:^(NSURLSession * _Nonnull session) { AppDelegate *appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate]; if (appDelegate.backgroundSessionCompletionHandler) { void (^completionHandler)() = appDelegate.backgroundSessionCompletionHandler; appDelegate.backgroundSessionCompletionHandler = nil; completionHandler(); } NSLog(@"All tasks are finished"); }]; 

在您的AppDelegate中添加以下代码:

  - (void)application:(UIApplication *)application handleEventsForBackgroundURLSession:(NSString *)identifier completionHandler:(void (^)())completionHandler { self.backgroundSessionCompletionHandler = completionHandler; //add notification [self presentNotification]; } -(void)presentNotification{ UILocalNotification* localNotification = [[UILocalNotification alloc] init]; localNotification.alertBody = @"Download Complete!"; localNotification.alertAction = @"Background Transfer Download!"; //On sound localNotification.soundName = UILocalNotificationDefaultSoundName; //increase the badge number of application plus 1 localNotification.applicationIconBadgeNumber = [[UIApplication sharedApplication] applicationIconBadgeNumber] + 1; [[UIApplication sharedApplication] presentLocalNotificationNow:localNotification]; } 

为你的2解决scheme

如果系统杀死了您的应用程序,并且您的后台会话有活动下载,则您的下载将继续,系统将在下载完成时启动您的应用程序。 但是,如果用户强制退出您的应用程序,所有任务将被取消。