Get the data from NSURLSession DownloadTaskWithRequest from completion handler

爱⌒轻易说出口 提交于 2019-11-30 13:04:04

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!