NSURL下载文件,指标显示为时已晚

时间:2014-06-08 23:09:00

标签: ios objective-c

您好我得到以下代码,并希望在下载时显示ActivityIndi​​cator。但该指标仅在下载完成时显示?

_fanDownloadIndicator.hidden = NO;
NSLog(@"batzn");
NSString *documentPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)objectAtIndex:0];
NSString *file = [documentPath stringByAppendingPathComponent:@"fan_new.mp3"];
BOOL fileExists = [[NSFileManager defaultManager]fileExistsAtPath:file];

if(fileExists == NO) {

    NSURL *downurl = [NSURL URLWithString:url];
    NSData *data = [NSData dataWithContentsOfURL:downurl];
    if ([data writeToFile:file atomically:YES]) {
        NSLog(@"downloaded fan");

1 个答案:

答案 0 :(得分:3)

问题

您正在主线程上执行下载任务,并等到线程结束后再显示加载视图。

解决方案

您需要使用dispatch_async开始在后台线程上下载任务。看看下面的代码

_fanDownloadIndicator.hidden = NO;
NSLog(@"batzn");
NSString *documentPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)objectAtIndex:0];
NSString *file = [documentPath stringByAppendingPathComponent:@"fan_new.mp3"];
BOOL fileExists = [[NSFileManager defaultManager]fileExistsAtPath:file];

if(fileExists == NO) {

//Show your loading view here

dispatch_async(dispatch_get_global_queue( DISPATCH_QUEUE_PRIORITY_HIGH, 0), ^{

            //Do your downloading here on background thread
            NSURL *downurl = [NSURL URLWithString:url];
            NSData *data = [NSData dataWithContentsOfURL:downurl];
            dispatch_async(dispatch_get_main_queue(), ^{
                if ([data writeToFile:file atomically:YES]) {
                    //Hide your loading view
                    NSLog(@"downloaded fan");
                }   
            });
        });
}

另外,我会为您的加载视图MBProgressHUD提供建议。以下是你可以用它做的事情

//Show loading form here
[MBProgressHUD showHUDAddedTo:self.view animated:YES];
dispatch_async(dispatch_get_global_queue( DISPATCH_QUEUE_PRIORITY_LOW, 0), ^{
    // Do something...
    dispatch_async(dispatch_get_main_queue(), ^{
        [MBProgressHUD hideHUDForView:self.view animated:YES];
    });
});

更新

如果您正在处理下载图像,我应该推荐这个库:

SDWebImage

它还提供第三方显示活动指标。