0

我正在使用一种方法来下载文档目录中的视频文件,它工作得非常好,我使用下面的代码在后台下载视频,但是在下载时我需要更新进度条,因为下载了多少,但是主线程是不更新。

dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{

    NSData *data = [NSData dataWithContentsOfURL: videoURL];

    NSString *pathToDocs = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
    NSString *filename = [NSString stringWithFormat:@"%@.mp4",self.titleString];
    [data writeToFile:[pathToDocs stringByAppendingPathComponent:filename] atomically:YES];
    NSLog(@"File %@ successfully saved", filename);

    UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"Alert" message:@"Succesfully Downloaded" delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil];
    [alertView show];

});
4

3 回答 3

2

尝试像这样在主线程上更新进度,

     dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{

        NSData *data = [NSData dataWithContentsOfURL: videoURL];

        NSString *pathToDocs = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
        NSString *filename = [NSString stringWithFormat:@"%@.mp4",self.titleString];
        [data writeToFile:[pathToDocs stringByAppendingPathComponent:filename] atomically:YES];
        NSLog(@"File %@ successfully saved", filename);

        UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"Alert" message:@"Succesfully Downloaded" delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil];
        [alertView show];

        dispatch_async(dispatch_get_main_queue(), ^(){
            //Task you want perform on mainQueue
            //Control Progressbar here

        });
    });
于 2013-03-04T06:21:35.880 回答
1

dataWithContentsOfURL不会返回状态;它只是阻塞线程,直到完成下载。您需要使用异步报告进度的东西。

看看 AFNetworking ( https://github.com/AFNetworking/AFNetworking#file-upload-with-progress-callback ),因为它旨在满足您的需求。

于 2013-03-04T06:14:14.573 回答
0

为了能够监控下载进度,您应该考虑使用NSURLConnection,您可以使用该NSURLConnectionDataDelegate方法didReceiveData更新您的 UI 以了解进度。

如果您想知道预期的数据量,您可以经常使用didReceiveResponse,对于 HTTP URL,它可能包含预期的文件大小。(不过,并非所有的 Web 服务器都提供。)

正如 Richard 建议的那样,您可能想考虑使用AFNetworking,因为它可以简化您的编程工作。

于 2013-03-04T06:14:40.820 回答