【发布时间】:2020-05-08 02:39:06
【问题描述】:
我有一个 ViewController,我从中下载 pdf 文档。
在下载时,我显示了一个 UIAlertController,其中包含一个 UIProgressView,我正在更新下载进度。第一次一切正常。
现在下载后,我按下导航栏中的后退按钮转到上一个 ViewController。然后当我再次前进到下载控制器并尝试再次下载时,进度没有更新,UIAlertController 也没有关闭。
问题只是当我回到以前的控制器时。如果我留在同一个控制器中并再次尝试下载,它可以工作。
public partial class WAReportController : UITableViewController
{
const string Identifier = "com.gch.DownloadDocument.BackgroundSession";
public NSUrlSessionDownloadTask downloadTask;
public NSUrlSession session;
public void DownloadReport()
{
if (session == null)
session = InitBackgroundSession();
using (var url = NSUrl.FromString(RestApiPaths.REPORT_DOWNLOAD_PATH))
using (var request = new NSMutableUrlRequest(url)) {
request.Headers = CommonUtils.GetHeaders();
downloadTask = session.CreateDownloadTask(request);
downloadTask.Resume();
ShowAlert();
}
}
public NSUrlSession InitBackgroundSession()
{
Console.WriteLine("InitBackgroundSession");
using (var configuration = NSUrlSessionConfiguration.CreateBackgroundSessionConfiguration(Identifier)) {
return NSUrlSession.FromConfiguration(configuration, (INSUrlSessionDelegate)new ReportDownloadDelegate(this), new NSOperationQueue());
}
}
public class ReportDownloadDelegate : NSUrlSessionDownloadDelegate
{
private WAReportController _vc;
public ReportDownloadDelegate(WAReportController vc)
{
_vc = vc;
}
public override void DidWriteData(NSUrlSession session, NSUrlSessionDownloadTask downloadTask, long bytesWritten, long totalBytesWritten, long totalBytesExpectedToWrite)
{
float progress = totalBytesWritten / (float)totalBytesExpectedToWrite;
Console.WriteLine(string.Format("progress: {0}", progress));
DispatchQueue.MainQueue.DispatchAsync(() => {
_vc.UpdateDownloadProgress(progress); // updates successfully only the first time
});
}
public override void DidFinishDownloading(NSUrlSession session, NSUrlSessionDownloadTask downloadTask, NSUrl location)
{
_vc.DismissDownloadProgressAlert();
}
}
UIAlertController downloadProgressAlert;
UIProgressView downloadProgress;
void ShowAlert()
{
downloadProgressAlert = UIAlertController.Create("Downloading", "\n\n", UIAlertControllerStyle.Alert);
downloadProgressAlert.AddAction(UIAlertAction.Create("Cancel", UIAlertActionStyle.Cancel, (action) => {
downloadTask.Cancel();
}));
PresentViewController(downloadProgressAlert, true, () => {
nfloat margin = 8.0f;
var rect = new CGRect(margin, 72.0f, downloadProgressAlert.View.Frame.Width - margin * 2.0f, 2.0f);
downloadProgress = new UIProgressView(rect) {
Progress = 0.0f,
TintColor = UIColor.Blue
};
downloadProgressAlert.View.AddSubview(downloadProgress);
});
}
public void UpdateDownloadProgress(float progress)
{
if (downloadProgress != null) {
downloadProgress.Progress = 50;
}
}
public void DismissDownloadProgressAlert()
{
if (downloadProgressAlert != null) {
InvokeOnMainThread(() => {
downloadProgressAlert.DismissViewController(false, null);
});
}
}
}
【问题讨论】:
标签: ios xamarin.ios nsurlsession