private async Task <string> DownloadFile(string url) { string path = string.Empty; try { var fileName = GetFileName(url); path = System.IO.Path.Combine(Path, fileName); int totalBytes = GetFileSize(url); using (var fileUrl = new Java.Net.URL(url)) { using (var stream = fileUrl.OpenStream()) { byte[] bytes = new byte[totalBytes]; int numBytesToRead = totalBytes; int numBytesRead = 0; while (numBytesToRead > 0) { // Read may return anything from 0 to numBytesToRead. int n = await stream.ReadAsync(bytes, numBytesRead, numBytesToRead); // Break when the end of the file is reached. if (n == 0) { //await Task.Yield(); break; } numBytesRead += n; numBytesToRead -= n; float percentage = (float)numBytesRead / (float)totalBytes; var message = new DownloadProgressMessage() { Percentage = percentage }; MessagingCenter.Send <DownloadProgressMessage>(message, "DownloadProgressMessage"); } File.WriteAllBytes(path, bytes); } } } catch (Exception ex) { Log.WriteLine(LogPriority.Error, "GetImageFromBitmap Error", ex.Message); } return(path); }
public override void DidWriteData(NSUrlSession session, NSUrlSessionDownloadTask downloadTask, long bytesWritten, long totalBytesWritten, long totalBytesExpectedToWrite) { float percentage = (float)totalBytesWritten / (float)totalBytesExpectedToWrite; var message = new DownloadProgressMessage() { BytesWritten = bytesWritten, TotalBytesExpectedToWrite = totalBytesExpectedToWrite, TotalBytesWritten = totalBytesWritten, Percentage = percentage }; MessagingCenter.Send <DownloadProgressMessage> (message, "DownloadProgressMessage"); }