0

我一直在寻找如何在图像下载时更新进度视图。我当前的下载代码是

ThreadPool.QueueUserWorkItem(new WaitCallback(RetrieveImage),(object)cell);

private void RetrieveImage(object val)
{
CustomViewCell cell = (CustomViewCell)val;
int i = 0;
//lock(_imgDict){
//if ( !_imgDict.ContainsKey(cell.imageUrl) )
//{
     NSUrl nsUrl = new NSUrl(cell.imageUrl);
     NSData data = NSData.FromUrl(nsUrl);
     if (data != null) {
InvokeOnMainThread (() => {
    cell.imgImageView.Image = new UIImage (data);
    i++;
    cell.ProgressBar.Progress = (float)(i + 1) / 3; 
    });
    //_imgDict.Add (cell.imageUrl, data);
} 
}

所有这一切都是在图像顶部显示进度条,完成了 75%。没有真正显示正在更新的进度?如何在图像仍在下载时使用此当前线程更新进度条。我看到了其他示例,但并不能真正理解它们。

编辑:

ThreadPool.QueueUserWorkItem(new WaitCallback(RetrieveImage),(object)cell); 

 ServicePointManager.ServerCertificateValidationCallback = delegate { return true; };
 using(var client = new WebClient())
 {
client.DownloadProgressChanged+= 
 delegate(object sender, DownloadProgressChangedEventArgs e)
    {
         if (e.TotalBytesToReceive != 0) {
        InvokeOnMainThread (() => {
        cell.PG.Progress = e.BytesReceived / 
                e.TotalBytesToReceive;
              });
             }
     };
client.DownloadDataCompleted += 
delegate(object sender, DownloadDataCompletedEventArgs e)
    {
      if(e.Result!=null)
          {
                NSData data = NSData.FromArray(e.Result);
           _imgDict.Add (cell.ImageUrl, data);
         InvokeOnMainThread (() => {
                  cell.PG.Hidden=true;
                  cell.imgImageView.Image =  UIImage.LoadFromData(data);
            });
     }
    else
    {
        InvokeOnMainThread (() => {
        cell.PG.Hidden=true;
                    cell.imgImageView.Image = UIImage.FromBundle("Images/retrydownload.png");
                    });
    }
 }; 
    client.DownloadDataAsync(new Uri(cell.ImageUrl));
}

现在有了这个更新的代码,我在下载时看不到进度条

4

1 回答 1

1

您将进度硬编码为 75%。在您的代码i == 0中,所以(float)(i + 1) / 3 = 1/3 = 0.75.

NSData.FromUrl()不支持简单的进度处理。如果你想坚持使用原生的东西,你将不得不继承NSUrlConnection和覆盖DidReceiveData().

或者,我建议您改用 WebClient,这是 .NET 下载内容的方式:

var client = new WebClient();
client.DownloadProgressChanged += (args) =>
{
Console.WriteLine("Downloaded {0} of {1} bytes", args.BytesReceived, args.TotalBytesToReceive);
};

client.DownloadFileCompleted += (args) => Console.WriteLine("Download finished.");
client.DownloadFileAsync(new Uri("someurl"), "somelocalpath");
于 2013-10-19T10:04:56.103 回答