2013-03-04 30 views
0

我使用一種方法下載文件目錄內的視頻文件,它工作得很好,我使用下面的代碼,它是在後臺下載視頻,但下載時需要更新進度條也是多少下載,但主線程沒有更新。如何從UIProgressBar在iOS主線程上更新

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]; 

}); 

回答

0

爲了能夠監視下載的進度,您應該考慮使用NSURLConnection,您可以在其中使用NSURLConnectionDataDelegate方法didReceiveData來更新您的UI有關進度。

如果您想知道預計有多少數據,您可以經常使用didReceiveResponse,對於HTTP URL,它可能包含預期的文件大小。 (儘管如此,並非所有的網絡服務器都提供這種服務。)

正如理查德建議的那樣,您可能需要使用AFNetworking,因爲它可以簡化您的編程工作。

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 

     }); 
    });