下载文件时显示进度条

时间:2014-08-02 04:49:43

标签: ios objective-c download mbprogresshud

您好我的应用程序我有一个URL文件我想下载到我的应用程序中的文档文件夹,同时下载文件我想显示进度条。所以我已经使用了MBProgressHUD,但它的工作效果不正常,请告诉我如何解决这个问题。

我的代码:

- (IBAction)down:(id)sender {
    UIButton *btn = (UIButton *)sender;

     spinner =  [MBProgressHUD showHUDAddedTo:self.view animated:YES];

     spinner.mode = MBProgressHUDModeCustomView;

     [spinner setLabelText:@"downloading....."];

     [spinner setLabelFont:[UIFont systemFontOfSize:15]];

     [spinner show:YES];
   NSURL  *url = [NSURL URLWithString:fileurl];
   NSData *urlData = [NSData dataWithContentsOfURL:url];


    if ( urlData )
     {

        NSArray       *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
        NSString  *documentsDirectory = [paths objectAtIndex:0];

        NSString  *filePath = [NSString stringWithFormat:@"%@/%@", documentsDirectory,name];
    [urlData writeToFile:filePath atomically:YES];
     }
   [activityIndicatorObject stopAnimating];
   [spinner hide:YES];

   [spinner removeFromSuperViewOnHide];

   }

我使用了上面的代码,花了太多时间来展示MBProgressHUD请告诉我如何解决这个问题我已经坚持了一段时间。

谢谢..

2 个答案:

答案 0 :(得分:0)

您必须更改以下代码..

   - (IBAction)down:(id)sender {
UIButton *btn = (UIButton *)sender;

 //spinner =  [MBProgressHUD showHUDAddedTo:self.view animated:YES];
   [MBProgressHUD showHUDAddedTo:self.view animated:YES];

 //spinner.mode = MBProgressHUDModeCustomView;

 //[spinner setLabelText:@"downloading....."];

 //[spinner setLabelFont:[UIFont systemFontOfSize:15]];

 //[spinner show:YES];
      NSURL  *url = [NSURL URLWithString:fileurl];
      NSData *urlData = [NSData dataWithContentsOfURL:url];


if ( urlData )
 {

    NSArray       *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString  *documentsDirectory = [paths objectAtIndex:0];

    NSString  *filePath = [NSString stringWithFormat:@"%@/%@", documentsDirectory,name];
[urlData writeToFile:filePath atomically:YES];
 }
   //[activityIndicatorObject stopAnimating];
   //[spinner hide:YES];

  //[spinner removeFromSuperViewOnHide];
  [MBProgressHUD hideHUDForView:self.view animated:YES];



  }

享受代码..

答案 1 :(得分:0)

我怀疑您遇到的是上述代码的并发问题。我假设您提取的网址来自网络。在微调器 setNeedsDisplay >,这也发生在主线程上,这可以解释为什么它出现的时间很晚。

解决方案是使用完成处理程序创建某种异步请求,以获取文件,这样您的应用程序就可以在完成时执行任务等,(比如停止活动指示器,将文件保存到本地存储等)

这是文档对 NSData 类的 dataWithContentsOfURL:所说的内容: -

  

重要提示:请勿使用此同步方法来请求基于网络的网址。对于基于网络的URL,此方法可以在慢速网络上阻止当前线程数十秒,从而导致用户体验不佳,而在iOS中,可能会导致应用程序被终止。   相反,对于非文件URL,请考虑使用NSSession类的dataTaskWithURL:completionHandler:方法。