I found a solution to this problem:
To get the status code in the response header, you must first run NSURLSessionDataTask .
This will call the following delegate method of URLSession: dataTask: didReceiveResponse: completeHandler:.
In this method, you can first check the status code of the NSURLResponse parameters (dropping it to NSHTTPURLResponse) and finally call the completion handler using NSURLSessionResponseBecomeDownload to convert your dataTask to downloadTask (which will behave the way you would expect from NSURLSessionDownloadTaskRancelance) to avoid loading some data that you do not need (for example, if the response status code is 404).
In addition, if you need to do something with the converted NSURLSessionDownloadTask (for example, save it in an array or dictionary or replace the data task with a new object), this can be done in URLSession: dataTask: didBecomeDownloadTask:
Hope this helps someone!
source share