从完成处理程序获取NSURLSession DownloadTaskWithRequest中的数据

时间:2022-04-23 21:00:47

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

所以我很难理解一些东西。这是我对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 :

    一般来说,我有两个选项(据我所知)DataTask(e)。x dataTaskWithRequest)和DownloadTask(e。使用它们的委托方法,或者使用完成处理程序,这两种方法都不行。我已经设法使用dataTaskWithRequest来接收数据,如下所示:

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

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. e.X

它的工作原理。问题是,我需要将数据下载到磁盘中,而不是只下载到内存中(我正在下载图像)。我对DownloadTaskWithRequest +他的完成处理器也做了同样的尝试,我注意到他接受的参数都是一样的,第一个是NSURL,在DataTaskWithRequest中是NSData,这让事情变得非常简单。e.X

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

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

我的问题是:我知道我可以使用以下方法从该位置(NSURL)获取数据:

    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?

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

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

2)这是正确的方法吗(我知道我可以使用委托方法,我不喜欢)?

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

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

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

谢谢你们! !不好意思,newibie的问题,我真的很关心效率-谢谢!

1 个解决方案

#1


14  

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.

使用下载任务时,通常只需使用下载任务的completionHandler提供的位置,使用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.

当然,也可以使用contentsOfURL将对象加载到NSData中。是的,它与当地资源一起工作。而且,不,它不会再提出要求……如果查看URL,它是本地文件系统中的文件URL。但是这样你就失去了下载任务的大部分内存节省,所以如果你真的想把数据任务放到NSData中,你可以使用它。但是,如果您想将它移动到持久存储,那么上面的模式可能是有意义的,避免使用NSData对象。

#1


14  

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.

使用下载任务时,通常只需使用下载任务的completionHandler提供的位置,使用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.

当然,也可以使用contentsOfURL将对象加载到NSData中。是的,它与当地资源一起工作。而且,不,它不会再提出要求……如果查看URL,它是本地文件系统中的文件URL。但是这样你就失去了下载任务的大部分内存节省,所以如果你真的想把数据任务放到NSData中,你可以使用它。但是,如果您想将它移动到持久存储,那么上面的模式可能是有意义的,避免使用NSData对象。