【问题标题】:Resume download functionality in NSURLConnection在 NSURLConnection 中恢复下载功能
【发布时间】:2010-03-16 06:37:55
【问题描述】:

我正在使用 NSURLConnection 类从服务器下载一些非常大的数据。

如何实现暂停功能以便继续下载?

【问题讨论】:

  • 您是否成功实现了暂停功能?

标签: iphone nsurlconnection nsurlrequest


【解决方案1】:

您本身不能暂停,但您可以取消连接,然后创建一个新连接以从旧连接处继续。但是,您要连接的服务器必须支持 Range 标头。将此设置为“bytes=size_already_downloaded-”,它应该会在您取消它的地方继续。

【讨论】:

    【解决方案2】:

    要继续下载并获取文件的其余部分,您可以通过执行以下操作在 HTTP 请求标头中设置 Range 值:

    - (void)downloadFromUrl:(NSURL*)url toFilePath:(NSString *)filePath {
    
        NSMutableURLRequest *request = [[NSMutableURLRequest alloc]initWithURL:url     cachePolicy:NSURLRequestReloadIgnoringCacheData timeoutInterval:10];
        if (!request) {
            NSLog(@"Error creating request");
            // Do something
        }
        [request setHTTPMethod:@"GET"];
    
        // Add header to existing file
        NSFileManager *fm = [NSFileManager defaultManager];
        if([fm fileExistsAtPath:filePath]) {
            NSError *error = nil;      
            NSDictionary * fileProp = [fm attributesOfItemAtPath:filePath error:&error];
            if (error) {
                NSLog(@"Error: %@", [error localizedDescription]);
                // Do something
            } else {
                // Set header to resume 
                long long fileSize = [[fileProp objectForKey:@"NSFileSize"]longLongValue];
                NSString *range = @"bytes=";
                range = [[range stringByAppendingString:[[NSNumber numberWithLongLong:fileSize] stringValue]] stringByAppendingString:@"-"];
                [request setValue:range forHTTPHeaderField:@"Range"];
            }
        }
        NSURLConnection * connection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
    
        if (!connection) {
            NSLog(@"Connection failed.");
            // Do something
        }
    }
    

    您还可以使用 - (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response 通过检查预期大小来检查现有文件是否已完全下载:[response expectedContentLength];。如果大小匹配,您可能想要取消连接。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-08-08
      • 2023-04-05
      • 1970-01-01
      • 2014-10-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多