ios - 使用附加 :YES with operation. outputStream AFHTTPRequestOperation 不起作用

标签 ios download afhttprequestoperation

我正在尝试下载一个文本文件,如果此下载暂停,我将尝试附加文件的其余部分。

问题是我开始从正确的位置下载其余部分,但文件没有附加它会覆盖以前的文件。

这是我的源代码: +(无效)下载文件:(NSManagedObject *)文件{

NSString *url = [file valueForKey:@"path"];

NSString *fileName = [[file valueForKey:@"path"] lastPathComponent]; // TODO chnage to file ID (it will be good to add id before file name)

NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *filePath = [[paths objectAtIndex:0] stringByAppendingPathComponent:fileName];

NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:url]];

BOOL append = NO;
unsigned long long size = 0;
BOOL resumeOperation = NO;
if ([[NSFileManager defaultManager] fileExistsAtPath:filePath]) {
    resumeOperation = YES;
    NSError *error = nil;
    NSDictionary *dict = [[NSFileManager defaultManager] attributesOfItemAtPath:filePath error:&error];
    size = [[dict objectForKey:NSFileSize] longLongValue];

    if (!error) {
        error = nil;
        [[NSFileManager defaultManager] removeItemAtPath:filePath error:&error];

        if (error) {
            NSLog(@"Error removing old file: %@", [error localizedDescription]);
        }

        NSString *val = [NSString stringWithFormat:@"bytes=%lld-", size];
        append = YES;
        [request setValue:val forHTTPHeaderField:@"Range"];
    }

}

AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request] ;


operation.outputStream = [NSOutputStream outputStreamToFileAtPath:filePath append:YES];


//gives more 10 minuts when the app is minimmized
[operation setShouldExecuteAsBackgroundTaskWithExpirationHandler:^{
    [operation pause];
}];

[operation setDownloadProgressBlock:^(NSUInteger bytesRead, long long totalBytesRead, long long totalBytesExpectedToRead) {
    totalBytesRead += size;
    float percent = ((float)totalBytesRead) / (totalBytesExpectedToRead + size);

 //        TODO update database with bytes amount
       NSLog(@"%.2f%% - [%d]", percent * 100, [[CoreDataManager getQueue] count]);
    }];

    [operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id      responseObject) {
    NSLog(@"File downloaded succesffully!");
    [self reportEndDownload:file withStatusCode:[NSNumber numberWithInt:DOWNLAOD_STATUS_COMPLETE]];
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
//        NSLog(@"Error while downloading file: %@", [error localizedDescription]);
//        ? ask about server corrupted files - here is a loop -----> Itay OK
    [self reportEndDownload:file withStatusCode:[NSNumber numberWithInt:DOWNLOAF_STATUS_CONNECTION_ERROR]];
}];

 if (resumeOperation ) {
     [operation resume];
 }else{
     [operation start];
 }


}

最佳答案

您可以使用 AFDownloadRequestOperation 来执行此操作。

NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:@"....zip"]];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *path = [[paths objectAtIndex:0] stringByAppendingPathComponent:@"....zip"];
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);
}];
[operation setProgressiveDownloadProgressBlock:^(NSInteger bytesRead, long long totalBytesRead, long long totalBytesExpected, long long totalBytesReadForFile, long long totalBytesExpectedToReadForFile) {
    NSLog(@"Operation%i: bytesRead: %d", 1, bytesRead);
    NSLog(@"Operation%i: totalBytesRead: %lld", 1, totalBytesRead);
    NSLog(@"Operation%i: totalBytesExpected: %lld", 1, totalBytesExpected);
    NSLog(@"Operation%i: totalBytesReadForFile: %lld", 1, totalBytesReadForFile);
    NSLog(@"Operation%i: totalBytesExpectedToReadForFile: %lld", 1, totalBytesExpectedToReadForFile);
}];
[operations addObject:operation];

关于ios - 使用附加 :YES with operation. outputStream AFHTTPRequestOperation 不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20881923/

相关文章:

iphone - 没有背景图片的 UINavigationBar 样式

java - 为什么我看不到下载百分比?

ios - 无法通过 NSOutputStream 将数据保存在文档目录的给定路径中

ios - 当我为 AFNetworking 设置我的 downloadProgressBlock 时,它只会在最后调用一次

ios - 为什么取消 AFHTTPRequestOperation 有时会遇到成功 block ?

ios - 将JSON响应分配给模型SwiftUI

c# - 是否可以在不使用 Itunes 的情况下从 Windows PC 访问 IOS 设备

ios - 搜索时将结果加载到表上

html - 使用 cordova-2.9.0 在 Android 中无法下载文件

c++ - 使用 Libcurl 从 FTP 服务器文件下载多个文件