Get the data from NSURLSession DownloadTaskWithRequest from completion handler

后端 未结 1 1390
甜味超标
甜味超标 2021-01-02 05:47

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) <

相关标签:
1条回答
  • 2021-01-02 06:18

    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 {
            print(error)
            return
        }
    
        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 {
            print(error)
        }
    }
    task.resume()
    

    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.

    0 讨论(0)
提交回复
热议问题