AFNetworking 2.0.0在后台下载

时间:2014-03-13 09:50:07

标签: ios objective-c afnetworking-2

我使用'AFNetworking', '2.0.0'下载数据。

我需要下载大文件。当用户锁定屏幕或按下主页按钮时,它应该暂停(或继续在后台下载),如果我返回应用程序,它应该恢复。

另外,我需要显示下载的进度。

我搜索了很多例子,但找不到任何'AFNetworking', '2.0.0'

我为iOS 6.0版创建了应用,因此我无法使用AFHTTPSessionManagerAFURLSessionManager

3 个答案:

答案 0 :(得分:3)

要使用NSURLSession NSURLSessionDownloadTask使用- (BOOL)application:(UIApplication* )application didFinishLaunchingWithOptions:(NSDictionary* )launchOptions,请在iOS 7或更高版本的后台下载。

在ProjectNavigator中打开BackgroundMode-> YourProject-> YourTarget->功能(标签) - >背景模式 enter image description here

使用下一代码添加到您的AppDelegate方法NSURLSessin NSURLSessionConfiguration *sessionConfiguration; NSString *someUniqieIdentifierForSession = @"com.etbook.background.DownloadManager"; if ([[[[[UIDevice currentDevice] systemVersion] componentsSeparatedByString:@"."] firstObject] integerValue] >= 8) { //This code for iOS 8 and greater sessionConfiguration = [NSURLSessionConfiguration backgroundSessionConfigurationWithIdentifier:someUniqieIdentifierForSession]; } else { this code for iOS 7 sessionConfiguration = [NSURLSessionConfiguration backgroundSessionConfiguration:someUniqieIdentifierForSession]; } sessionConfiguration.HTTPMaximumConnectionsPerHost = 5; self.session = [NSURLSession sessionWithConfiguration:sessionConfiguration delegate:self delegateQueue:[NSOperationQueue mainQueue]]; 的初始化程序:

session

当然,不要忘记用以下内容声明@property (nonatomic, strong) NSURLSession session; 属性:

@property (nonatomic, copy) void(^backgroundTransferCompletionHandler)();

还添加完成处理程序属性(如果您希望在应用程序终止或崩溃后获得后台下载进程的回调,则需要它:)

-(void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didFinishDownloadingToURL:(NSURL *)location{

    NSError *error;
    NSFileManager *fileManager = [NSFileManager defaultManager];

    NSString *destinationFilename = downloadTask.originalRequest.URL.lastPathComponent;
    NSURL *destinationURL = [[[[NSFileManager defaultManager] URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask] lastObject] URLByAppendingPathComponent:destinationFilename];

    if ([fileManager fileExistsAtPath:[destinationURL path]]) {
        [fileManager removeItemAtURL:destinationURL error:nil];
    }
    [fileManager copyItemAtURL:location
                         toURL:destinationURL
                         error:&error];
}

-(void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didCompleteWithError:(NSError *)error{
    if (error != nil) {
        NSLog(@"Download completed with error: %@", [error localizedDescription]);
    }
    else{
        NSLog(@"Download finished successfully.");
}

-(void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didWriteData:(int64_t)bytesWritten totalBytesWritten:(int64_t)totalBytesWritten totalBytesExpectedToWrite:(int64_t)totalBytesExpectedToWrite{

    if (totalBytesExpectedToWrite == NSURLSessionTransferSizeUnknown) {
        NSLog(@"Unknown transfer size");
    }
    else{
        NSLog(@"progress = %lld Mb of %lld Mb", totalBytesWritten/1024/1024, totalBytesExpectedToWrite/1024/1024);
    }
}

-(void)URLSessionDidFinishEventsForBackgroundURLSession:(NSURLSession *)session{
    ETBAppDelegate *appDelegate = [UIApplication sharedApplication].delegate;

    // Check if all download tasks have been finished.
    [self.session getTasksWithCompletionHandler:^(NSArray *dataTasks, NSArray *uploadTasks, NSArray *downloadTasks) {

        if ([downloadTasks count] == 0) {
            if (appDelegate.backgroundTransferCompletionHandler != nil) {
                // Copy locally the completion handler.
                void(^completionHandler)() = appDelegate.backgroundTransferCompletionHandler;

                // Make nil the backgroundTransferCompletionHandler.
                appDelegate.backgroundTransferCompletionHandler = nil;

                [[NSOperationQueue mainQueue] addOperationWithBlock:^{
                    // Call the completion handler to tell the system that there are no other background transfers.
                    completionHandler();

                    // Show a local notification when all downloads are over.
                    UILocalNotification *localNotification = [[UILocalNotification alloc] init];
                    localNotification.alertBody = @"All files have been downloaded!";
                    [[UIApplication sharedApplication] presentLocalNotificationNow:localNotification];
                }];
            }
        }
    }];
}


//Background download support (THIS IMPORTANT METHOD APPLICABLE ONLY IN YOUR AppDelegate.m FILE!!!)
-(void)application:(UIApplication *)application handleEventsForBackgroundURLSession:(NSString *)identifier completionHandler:(void (^)())completionHandler{
    self.backgroundTransferCompletionHandler = completionHandler;
}

在AppDelegate中添加委托方法:

NSURLSessionDelegate

并声明您的类(在我的示例的AppDelegate.h文件中)符合协议@interface AppDelegate : UIResponder <UIApplicationDelegate, NSURLSessionDelegate> ,如下所示:

NSURLSessionDownloadTask *task = [self.session downloadTaskWithURL:[NSURL URLWithString:urlString]];
task.taskDescription = [NSString stringWithFormat:@"Downloading file %@", [urlString lastPathComponent]];
[task resume];

然后使用以下内容添加下载任务:

{{1}}

因此,当您的应用程序在终止后启动时,将恢复您的会话并触发委托方法。此外,如果您的应用程序将从后台唤醒到前台,您的应用程序委托方法也将被触发。

答案 1 :(得分:1)

当你的应用程序进入后台暂停/停止下载操作时,当进入前台时,在NSOperation队列中恢复暂停的下载操作。 阅读这些代码可能会对您有所帮助:

        AFDownloadRequestOperation *operation = [[AFDownloadRequestOperation alloc] initWithRequest:request targetPath:filePath shouldResume:YES];




        [operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
            //handel completion
            [operations removeObjectForKey:audioItem.filename];

        }failure:^(AFHTTPRequestOperation *operation, NSError *error) {
            //handel failure
                    operation = [operations objectForKey:audioItem.filename];
                    [operation cancel];
                    [operations removeObjectForKey:audioItem.filename];
                    if (error.code != NSURLErrorCancelled) {
                        [self showErrorAlert];
                        NSLog(@"Error: %@", error);
                    }




        }];


    [operation setProgressiveDownloadProgressBlock:^(NSInteger bytesRead, long long totalBytesRead, long long totalBytesExpected, long long totalBytesReadForFile, long long totalBytesExpectedToReadForFile) {
            //handel progress
            NSNumber *progress = [NSNumber numberWithFloat:((float)totalBytesReadForFile / (float)totalBytesExpectedToReadForFile)];
            float progress=progress.floatValue;
            [self performSelectorOnMainThread:@selector(updateProgressBar:) withObject:[NSArray arrayWithObjects:audioItem, progress, nil] waitUntilDone: YES];

        }];

        [operation setShouldExecuteAsBackgroundTaskWithExpirationHandler:^{
            // TODO: Clean up operations
            NSLog(@"App has been in background too long, need to clean up any connections!");
        }];

        [operations setValue:operation forKey:@"key"]; // store the NSOperation for further use in application to track its status.
        [downloadQueue addOperation:operation];//here downloadQueue is NSOperationQueue instance that manages NSOperations.

要暂停下载操作,请使用:

[operation pause];

要恢复使用此类行:

[operation resume];

答案 2 :(得分:0)

也许你最好使用DTDownload: https://github.com/Cocoanetics/DTDownload

据我所知,它没有任何报告进展的信息。

编辑:在AppCoda上有一个很好的教程,关于使用NSURLSessionTask: http://www.appcoda.com/background-transfer-service-ios7/