从完成处理程序中获取NSURLSession DownloadTaskWithRequest中的数据 [英] Get the data from NSURLSession DownloadTaskWithRequest from completion handler

查看:137
本文介绍了从完成处理程序中获取NSURLSession DownloadTaskWithRequest中的数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我很难理解某些事情。这是我对NSURSession的理解:

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


  • 一般来说,我有2个选项(据我所知) DataTask(ex dataTaskWithRequest) DownloadTask(ex DownloadTaskWithRequest ) - 使用他们的委托方法,使用完成处理程序,不能同时执行这两种操作。
    我设法使用dataTaskWithRequest接收DATA,如下所示:

  • Generally , I have 2 options for (as far as I know) DataTask(e.x dataTaskWithRequest) And DownloadTask(e.x DownloadTaskWithRequest) - Using their delegate method , or use the completion handler , Can't 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 {
        println("error=\(error)")
        return
    }
    if data != nil {
        println("works")
        //Handle data


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


}
task.resume()      


完美无缺。问题是我需要 DOWNLOAD 数据到磁盘而不仅仅是内存(我正在下载图像)。所以我尝试使用 DownloadTaskWithRequest +他的完成处理程序,我注意到他所采用的参数与第一个 NSURL DataTaskWithRequest相同 NSData ,因此它使事情变得更加简单。
ex。

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. ex.

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

            //How do I get the data??
        })
task2.resume()

我的问题是这样的:我知道我可以使用以下方式从位置(NSURL)获取DATA:

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

    var data = NSData(contentsOfURL: location)

1) contentsOfURL 会让另一个请求获取这些数据,还是他在本地工作?如果它再次发送请求,我该如何避免呢?

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)这是正确的方法(我知道我可以使用委托方法,我不喜欢)?

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

3)如何在本地存储我已下载的数据(在问题1和2回答之后),并在需要时访问它?

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 newbie question , I really do care about efficient - Thank you!

推荐答案

使用下载任务时,一般只需使用位置由下载任务的 completionHandler 提供,只需使用<$ c将文件从其临时位置移动到您选择的最终位置(例如,移至Documents或Cache文件夹) $ C>的NSFileManager 。

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

您当然也可以使用<$ c $将对象加载到 NSData 中C> contentsOfURL 。是的,它适用于本地资源。并且,不,它不会发出另一个请求...如果您查看URL,它是本地文件系统中的文件URL。但是你会失去下载任务的大部分内存节省,所以你可能会使用数据任务,如果你真的想把它变成 NSData 。但是如果你想将它移动到持久存储,上面的模式可能是有意义的,避免完全使用 NSData 对象。

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.

这篇关于从完成处理程序中获取NSURLSession DownloadTaskWithRequest中的数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆