Search code examples
iosobjective-cnsurlsessiondownloadtask

Error message on NSURLSessionDownloadDelegate Protocol


I am actually handling download/upload file and keeping tracked of the progress. It's working well. However, I am just wondering what if something goes wrong and I don't see any methods in this delegate handling the error. Here is the methods from NSURLSessionDownloadDelegate:

/*
 * Messages related to the operation of a task that writes data to a
 * file and notifies the delegate upon completion.
 */
@protocol NSURLSessionDownloadDelegate <NSURLSessionTaskDelegate>

/* Sent when a download task that has completed a download.  The delegate should 
 * copy or move the file at the given location to a new location as it will be 
 * removed when the delegate message returns. URLSession:task:didCompleteWithError: will
 * still be called.
 */
- (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask
                              didFinishDownloadingToURL:(NSURL *)location;

@optional
/* Sent periodically to notify the delegate of download progress. */
- (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask
                                           didWriteData:(int64_t)bytesWritten
                                      totalBytesWritten:(int64_t)totalBytesWritten
                              totalBytesExpectedToWrite:(int64_t)totalBytesExpectedToWrite;

/* Sent when a download has been resumed. If a download failed with an
 * error, the -userInfo dictionary of the error will contain an
 * NSURLSessionDownloadTaskResumeData key, whose value is the resume
 * data. 
 */
- (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask
                                      didResumeAtOffset:(int64_t)fileOffset
                                     expectedTotalBytes:(int64_t)expectedTotalBytes;

@end

Just wondering how to throw back the error message, thanks.


Solution

  • Have your delegate conform to NSURLSessionTaskDelegate and implement:

    - (void)URLSession:(NSURLSession *)session
                  task:(NSURLSessionTask *)task
    didCompleteWithError:(NSError *)error
    

    EDIT to clarify further, please see the doc for NSURLSessionDownloadDelegate, notice near the top where it says:

    In addition to these methods, be sure to implement the methods in the NSURLSessionTaskDelegate and NSURLSessionDelegate protocols to handle events common to all task types and session-level events, respectively.

    The idea is that the url session's delegate may conform any of those protocols. The method you're looking for, the one that indicates error, is just more generic than a download task, it can happen on any sort of session task, so they put it in a more abstract protocol.