您好我得到以下代码,并希望在下载时显示ActivityIndicator。但该指标仅在下载完成时显示?
_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");
答案 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];
});
});
如果您正在处理下载图像,我应该推荐这个库:
它还提供第三方显示活动指标。