2017-03-24 65 views
1

我使用Xamarin-CrossDownloadManager(https://github.com/SimonSimCity/Xamarin-CrossDownloadManager),我需要等待下载文件。我有这样的代码:Xamarin-CrossDownloadManager - 等待下载文件

private static async Task<bool> FileDownloadedTest(string LinkToFile, string PathFile) 
    { 
     var downloadManager = CrossDownloadManager.Current; 
     CrossDownloadManager.Current.PathNameForDownloadedFile = new System.Func<IDownloadFile, string>(file => { 
      return PathFile; 
     }); 
     { 
      await DeleteFile(PathFile); 
      var file = downloadManager.CreateDownloadFile(LinkToFile); 
      await Task.Run(() => downloadManager.Start(file, true)); //why this not wait??? 
     }   
     bool FileExist = await IsFileExist(PathFile); 
     return FileExist;  
    } 

为什么不等待完成下载操作?怎么做?

在他们编写的库站点上,我可以看到IDownloadManager.Queue在下载文件时获取信息。但是,我不知道如何在我的方法中使用这个...你能帮助我吗?

PS:对不起,我的英语,我还在学习它;)

回答

1

与该库,没有回调或事件公布了当一个文件被下载完成,但你可以做一个简单的检查并等待更多的循环。

await Task.Run(async() => 
{ 
    var downloadManager = CrossDownloadManager.Current; 
    var file = downloadManager.CreateDownloadFile(someFileBasedUrl); 
    downloadManager.Start(file); 
    bool isDownloading = true; 
    while (isDownloading) 
    { 
     await Task.Delay(10 * 1000); 
     isDownloading = IsDownloading(file); 
    } 
}); 

IsDownloading方法:

bool IsDownloading(IDownloadFile file) 
{ 
    if (file == null) return false; 

    switch (file.Status) 
    { 
     case DownloadFileStatus.INITIALIZED: 
     case DownloadFileStatus.PAUSED: 
     case DownloadFileStatus.PENDING: 
     case DownloadFileStatus.RUNNING: 
      return true; 

     case DownloadFileStatus.COMPLETED: 
     case DownloadFileStatus.CANCELED: 
     case DownloadFileStatus.FAILED: 
      return false; 
     default: 
      throw new ArgumentOutOfRangeException(); 
    } 
} 

回复:https://github.com/SimonSimCity/Xamarin-CrossDownloadManager/blob/develop/Sample/DownloadExample/Downloader.cs#L46

+0

该循环在下载文件后不停止。它适用于您的设备? – luki

+0

@luki在iOS上测试它...监视器'IDownloadFile.Status',下载完成后'Status'的值是多少? – SushiHangover

+0

在循环中:Debug.WriteLine(file.Status); - > RUNNING – luki

0

我不知道为什么IDownloadFile.Status =未完成的工作,但我发现解决问题:

await Task.Run(() => 
     { 
      var downloadManager = CrossDownloadManager.Current; 
      var file = downloadManager.CreateDownloadFile(LinkToFile); 
      downloadManager.Start(file); 
      while (file.Status == DownloadFileStatus.INITIALIZED) 
      { 
       while (file.TotalBytesExpected > file.TotalBytesWritten) 
       { 
        Debug.WriteLine(file.Status); 
       } 
      } 
     });   

有人知道为什么DownloadFileStatus.INITIALIZED工作,但DownloadFileStatus .COMPLETED不是?