Confused with NSURLSession delegate

0
class ImageTrack {

    var session: NSURLSession?
    var delegate: NSURLSessionDelegate?
    var task: NSURLSessionDownloadTask?

    func update() {
        let config = NSURLSessionConfiguration.defaultSessionConfiguration()

        session = NSURLSession(configuration: config, delegate: delegate!, delegateQueue: NSOperationQueue())
    }

    func searchImage() {
        if task != nil {
            task?.cancel()
        }

        let url = NSURL(string: "http://www.raywenderlich.com/wp-content/uploads/2015/08/Screen-Shot-2015-08-20-at-12.27.21-am.png")!
        task = session!.downloadTaskWithURL(url)

        task?.resume()
    }

}

I do not understand how it is possible that if the init of NSURLSession asks me for a delegate of the type NSURLSessionDelegate , I can call the methods of a child protocol as it would be with NSURLSessionDownloadDelegate with the method:

func URLSession(session: NSURLSession, downloadTask: NSURLSessionDownloadTask, didFinishDownloadingToURL location: NSURL).

EDIT My question is about the delegate variable of the NSURLSession which is of type NSURLSESSIONDELEGATE and that is not a NSURLSessionDownloadDelegate (although it is the other way around), so unless you cast it (delegate) you can not call NSURLSessionDownloadDelegate methods. So my question is: Is a cast internally in the code?

    
asked by MatiEzelQ 22.06.2016 в 01:52
source

1 answer

0

It is not entirely clear to me who is delegate in the code of the question ...

In any case, if the constructor expects an object of type NSURLSessionDelegate , you can pass an object that implements NSURLSessionDownloadDelegate since there is inheritance of protocols ...

I imagine the code would look something like this:

public class ImageTrack: NSObject, NSURLSessionDownloadDelegate {
    var session: NSURLSession?
    var task: NSURLSessionDownloadTask?

    func update() {
        let config = NSURLSessionConfiguration.defaultSessionConfiguration()

        session = NSURLSession(configuration: config, delegate: self, delegateQueue: NSOperationQueue())
    }

    public func URLSession(session: NSURLSession, downloadTask: NSURLSessionDownloadTask, didFinishDownloadingToURL location: NSURL) {
        // ...
    }
}
    
answered by 22.06.2016 в 14:18