How do I get the data from a finished `NSURLSessionDataTask`?

我与影子孤独终老i 提交于 2019-12-05 13:42:38

Yes, you have to manually piece the data together (or you can stream it to a file if it's really big and you don't want it taking up memory).

So, didReceiveData method will be returning your data as it comes in. So you should have instantiated a NSMutableData (for example, in didReceiveResponse) to which didReceiveData will append the data as it comes in. When didCompleteWithError is called, assuming the error is nil, you can be confident that your NSMutableData now contains all of the data received. As you noted, the challenge is keeping track of all of the 50+ downloads, so I maintain an dictionary keyed by task identifiers to keep track of which to append the data to. (Personally, I think it's a design flaw that NSURLSession implements the task, download, and upload delegates at the session level, rather than letting us instantiate separate task delegate objects for each task. But we're stuck with what we've got.)

If you're just downloading the data, the NSURLSessionDownloadTask is a great alternative (and is more efficient in terms of memory usage than just appending to NSMutableData instances), and you can conceivably also use a background session if you want (which you can't with a NSURLSessionDataTask).

Finally, if you're really doing 50+ downloads, you might want to consider wrapping the download tasks in NSOperation subclass so you can constrain how many run concurrently without risking having any timeout.

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