Jackky White Jackky White - 2 years ago 528
Swift Question

Get the data from NSURLSession DownloadTaskWithRequest from completion handler

So i'm having hard time understanding something. This are the things i understand about NSURSession :

  • Generally , I have 2 options for (as far as i know) DataTask(e.x dataTaskWithRequest) And DownloadTask(e.x DownloadTaskWithRequest) - Using thier delegate method , or use the completion handler , Cant do both.
    I have managed to receive DATA using dataTaskWithRequest like this :

    let request = NSMutableURLRequest(URL: dataSourceURL!)
    request.HTTPMethod = "POST"

    let postString = "lastid=\(id)"
    request.HTTPBody = postString.dataUsingEncoding(NSUTF8StringEncoding)
    let task = NSURLSession.sharedSession().dataTaskWithRequest(request) {
    data, response, error in

    if error != nil {
    if data != nil {
    //Handle data

    //println("response = \(response)")


It works perfectly. The problem is that i need to DOWNLOAD the data to the disk and not only to the memory(I'm downloading images). So i tried the same with DownloadTaskWithRequest + his completion handler and i have noticed that the parameters he takes are the same expect the first one which is NSURL and in DataTaskWithRequest is NSData so it makes things very simpler.

let task2 = NSURLSession.sharedSession().downloadTaskWithRequest(request, completionHandler: { (location : NSURL!, response : NSURLResponse!, error : NSError?) -> Void in
if error != nil {

//How do i get the data??

My Question is this : I know i can fetch the DATA out of the Location(NSURL) using :

var data = NSData(contentsOfURL: location)

1)Will contentsOfURL will make another "request" do get this data , or that he is working locally? If it sending request again , how can i avoid it?

2)Is this the right way(I know i can use the delegate methods, I prefer not)?

3)How can i store the data i have downloaded(after questions number 1 and 2 answered) locally , and access it if needed?

Thank you guys!! Sorry for newibie question , I really do care about efficient - Thank you!

Rob Rob
Answer Source

When using download tasks, generally one would simply use the location provided by the completionHandler of the download task to simply move the file from its temporary location to a final location of your choosing (e.g. to the Documents or Cache folder) using NSFileManager.

let task = NSURLSession.sharedSession().downloadTaskWithURL(url) { location, response, error in
    guard location != nil && error == nil else {

    let fileManager = NSFileManager.defaultManager()
    let documents = try! fileManager.URLForDirectory(.DocumentDirectory, inDomain: .UserDomainMask, appropriateForURL: nil, create: false)
    let fileURL = documents.URLByAppendingPathComponent("test.jpg")
    do {
        try fileManager.moveItemAtURL(location!, toURL: fileURL)
    } catch {

You certainly could also load the object into a NSData using contentsOfURL. Yes, it works with local resources. And, no, it won't make another request ... if you look at the URL it is a file URL in your local file system. But you lose much of the memory savings of download tasks that way, so you might use a data task if you really wanted to get it into a NSData. But if you wanted to move it to persistent storage, the above pattern probably makes sense, avoiding using a NSData object altogether.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download