2013-10-19 115 views
0

我一直在尋找所有看圖像下載時如何更新progressview。我的當前下載的代碼是UIProgressView跟蹤狀態下載ios monotouch

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)); 
} 

現在有了這個更新的代碼我沒有看到進度條,同時下載

回答

1

你硬編碼進度75%。 在你的代碼i == 0,所以(float)(i + 1)/3 = 1/3 = 0.75

NSData.FromUrl()不支持進度處理的簡單方法。如果你想堅持原生的東西,你必須繼承NSUrlConnection,並覆蓋DidReceiveData()

另外,我建議你使用Web客戶端來代替,這是下載東西的.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"); 
+0

我會避免WebClient的,因爲它執行的UI線程大部分工作,而堅持這一:https://github.com/paulcbetts/ModernHttpClient –

+0

那麼我喜歡我的方式通過ios方式.Net方式的原因是,如果URL無效,NSData = null;我對UI做了一些不同的事情,.net對於webclient不起作用。我將如何去將NSLUrlConnection合併到我的代碼中,你能否提供一些方向 – Jake

+0

另外,如何在文件完成時隱藏進度條,因爲將Frame更改爲(0,0,0,0)並不完全它 – Jake