-1

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

谢谢

//全局头变量

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;
}
4

1 回答 1

2

将您的下载代码封装到NSOperation. 然后您可以使用 anNSOperationQueue异步运行下载,允许并行完成一定数量的下载,等等。

我没有读过这个教程,但它看起来很透彻:http ://www.raywenderlich.com/19788/how-to-use-nsoperations-and-nsoperationqueues

于 2013-04-17T14:20:28.987 回答