在ios sdk中同时下载多个视频文件

时间:2013-04-17 13:35:33

标签: ios ipad

我必须同时从服务器下载多个文件。目前我一次下载一个视频,它的工作完全正常。下面是相同的代码。现在我需要同时下载多个视频,并为正在进行的所有下载维护单独的进度条。这段代码可以下载大型视频,也可以采用更好的方法。

由于

//全局标题变量

float contentSize;
NSMutableData *responseAsyncData;
UIProgressView *progressBar;

//创建连接的代码

NSString *requestString = [NSMutableString stringWithString:VIDEO_LINK];
NSMutableURLRequest *urlRequest = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:requestString] cachePolicy:NO timeoutInterval:15.0];
NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:urlRequest delegate:self startImmediately:YES];

并处理这样的回调..

- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {

    if ([response isKindOfClass:[NSHTTPURLResponse class]])
    {
        NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *) response;
        contentSize = [httpResponse expectedContentLength];
    }
}

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {

    if(responseAsyncData==nil)
    {
        responseAsyncData = [[NSMutableData alloc] initWithLength:0];
    }
    [responseAsyncData appendData:data];
    float progress = (float)[responseAsyncData length] / (float)contentSize;
    [progressBar setProgress:progress];
}

- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
    NSLog(@"Error: %@", [error localizedDescription]);
}

- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
    NSError* error;

    if(responseAsyncData)
    {
       //filepath = Path to my location where i am storing
        BOOL pass = [responseAsyncData writeToFile:filepath atomically:YES];
        if (pass) {
            NSLog(@"Saved to file: %@", filepath);
        } else {
            NSLog(@"Video not saved.");
        }
        [progressBar setProgress:0];
    }
    responseAsyncData = nil;
}

1 个答案:

答案 0 :(得分:2)

将下载代码封装到NSOperation的子类中。然后,您可以使用NSOperationQueue异步运行下载,允许并行执行某个数字等。

我没有阅读本教程,但看起来非常透彻:http://www.raywenderlich.com/19788/how-to-use-nsoperations-and-nsoperationqueues