Search code examples
objective-cnsurlconnectionnsurlrequest

Cancelling an NSURLRequest


Is there a method provided in the native SDK to cancel the URL request made? I know this method:

[connection cancel]

But I am wondering if we can cancel a request. I only want to use the native SDK and I am not allowed to use the third party libraries. Also is there a way to track the progress of the download with the native library?


Solution

  • For the first part, you need to call cancel on the NSURLConnection as [connection cancel].

    As per NSURLRequest documentation:

    NSURLRequest encapsulates two basic data elements of a load request: the URL to load, and the policy to use when consulting the URL content cache made available by the implementation.

    And as per NSURLConnection documentation

    An NSURLConnection object provides support to perform the loading of a URL request. The interface for NSURLConnection is sparse, providing only the controls to start and cancel asynchronous loads of a URL request.

    So you are canceling a URL connection and not a URL request.

    For the second part, check the NSURLConnectionDownloadDelegate Protocol Reference. It has the following delegate methods for this purpose.

    – connection:didWriteData:totalBytesWritten:expectedTotalBytes:
    – connectionDidResumeDownloading:totalBytesWritten:expectedTotalBytes:
    – connectionDidFinishDownloading:destinationURL: