我创建了一个应用程序,可以从任何大小的url下载文件。我的页面中有一个按钮和一个进度视图。我想点击按钮下载的文件,并在进度视图中显示下载状态。
我可以使用此代码下载任何文件,但我不知道如何使用此代码使用进度视图:
- (IBAction)Download:(id)sender
{
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
NSLog(@"Downloading Started");
NSString *urlToDownload = @"http://192.168.1.100/emma/Adele%20-%20Someone%20Like%20You%20(MTV%20Video%20Music%20Awards%202011)%20HD%20Live.mkv";
NSURL *url = [NSURL URLWithString:urlToDownload];
NSData *urlData = [NSData dataWithContentsOfURL:url];
if ( urlData )
{
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *filePath = [NSString stringWithFormat:@"%@/%@", documentsDirectory,@"filename.mkv"];
dispatch_async(dispatch_get_main_queue(), ^{
[urlData writeToFile:filePath atomically:YES];
NSLog(@"File Saved !");
});
x = 1;
NSLog(@"x : %d",x);
}
});
}
请指导我。
答案 0 :(得分:2)
在.h文件中定义 NSTimer *计时器,并在 .xib
中设置 ProgressView- (IBAction)Download:(id)sender
{
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
NSLog(@"Downloading Started");
NSString *urlToDownload = @"http://192.168.1.100/emma/Adele%20-%20Someone%20Like%20You%20(MTV%20Video%20Music%20Awards%202011)%20HD%20Live.mkv";
NSURL *url = [NSURL URLWithString:urlToDownload];
NSData *urlData = [NSData dataWithContentsOfURL:url];
if ( urlData )
{
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *filePath = [NSString stringWithFormat:@"%@/%@", documentsDirectory,@"filename.mkv"];
timer = [NSTimer timerWithTimeInterval:0.5 target:self selector:@selector(updateProgressView) userInfo:nil repeats:YES];
[timer fire];
dispatch_async(dispatch_get_main_queue(), ^{
[urlData writeToFile:filePath atomically:YES];
NSLog(@"File Saved !");
});
x = 1;
NSLog(@"x : %d",x);
}
});
}
并添加此方法
- (void) updateProgressView{
NSString *urlToDownload = @"http://192.168.1.100/emma/Adele%20-%20Someone%20Like%20You%20(MTV%20Video%20Music%20Awards%202011)%20HD%20Live.mkv";
NSURL *url = [NSURL URLWithString:urlToDownload];
NSData *urlData = [NSData dataWithContentsOfURL:url];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *filePath = [NSString stringWithFormat:@"%@/%@", documentsDirectory,@"filename.mkv"];
NSData *writtenData = [NSData dataWithContentsOfFile:filePath];
float progress = [writtenData length]/(float)[urlData length];
[progressView setProgress:progress];
if (progress == 1.0){
[timer invalidate];
}
}