How to Cancel a NSUrlSessionDownloadTask

RobertDalyRobertDaly USMember ✭✭

I have tried to cancel an active task, but it never seems to stop until it is done. In the DidWriteData overload, I added the following when the user touches a Stop Button:

downloadTask.Cancel();
session.InvalidateAndCancel();

However, the DidWriteData still continues.

Is there something I am missing?

Here is the code:

public override void DidWriteData(NSUrlSession session, NSUrlSessionDownloadTask downloadTask, long bytesWritten, long totalBytesWritten, long totalBytesExpectedToWrite)
{
float progress100 = 0;

        Console.WriteLine("Set Progress");
        if (downloadTask == downloadTask)
         {
            float progress = totalBytesWritten / (float)totalBytesExpectedToWrite;
            Console.WriteLine(string.Format("DownloadTask: {0}  progress: {1}", downloadTask, progress));
            InvokeOnMainThread(() => {
                progress100 = progress * 100f;

                MainViewController._progressBar2.SetProgress((float)progress, true);

                string pctString = String.Format("{0:0.00}", progress100);
                MainViewController._uFileStatus.Text = "Downloading in progress: " + pctString + " %";

                if (MainViewController.cancelStatus == true)
                {
                    downloadTask.Cancel();
                    session.InvalidateAndCancel();

                }
            });
        }
    }
Tagged:

Answers

  • RobertDalyRobertDaly USMember ✭✭

    I think I figured it out. I had to add:
    controller.downloadTask = null;

    after the session.InvalidateAndCancel();

    I'll update if there are any issues.

  • RobertDalyRobertDaly USMember ✭✭

    No it doesn't work either. Only worked one time. Still trying and if someone has a suggestion it would be most welcome.

  • LandLuLandLu Member, Xamarin Team Xamurai

    How did you set this delegate to your session?
    I created a simple download task to test a video file like:

    partial void BtnClick(UIKit.UIButton sender)
    {
        NSUrlSession session = NSUrlSession.FromConfiguration(NSUrlSessionConfiguration.DefaultSessionConfiguration, new MySessionDelegate(this) as INSUrlSessionDelegate, NSOperationQueue.MainQueue);
        var downloadtask = session.CreateDownloadTask(new NSUrlRequest(new NSUrl("https://sample-videos.com/video123/mp4/720/big_buck_bunny_720p_30mb.mp4")));
    
        downloadtask.Resume();
    }
    
    // Delegate
    public class MySessionDelegate : NSUrlSessionDownloadDelegate
    {
        UIViewController viewController;
        public MySessionDelegate(UIViewController vc)
        {
            viewController = vc;
        }
        public override void DidFinishDownloading(NSUrlSession session, NSUrlSessionDownloadTask downloadTask, NSUrl location)
        {
    
        }
    
        public override void DidWriteData(NSUrlSession session, NSUrlSessionDownloadTask downloadTask, long bytesWritten, long totalBytesWritten, long totalBytesExpectedToWrite)
        {
            downloadTask.Cancel();
        }
    
        public override void DidCompleteWithError(NSUrlSession session, NSUrlSessionTask task, NSError error)
        {
            if (error != null)
            {
                UIAlertController alert = UIAlertController.Create("Title", "Task cancelled", UIAlertControllerStyle.Alert);
                alert.AddAction(UIAlertAction.Create("OK", UIAlertActionStyle.Default, null));
                viewController.PresentViewController(alert, true, null);
            }            
        }
    }
    

    The completion event will be triggered:

Sign In or Register to comment.