如何从互联网下载文件并保存在“文档”中在 iPhone 上?
我的远程服务器上有一个文件夹,其中有一些 .png 文件。我想从我的应用程序中下载这些并将它们存储在应用程序的“文档”文件夹中。我该怎么做?
I have a folder on my remote server that has a few .png files in it. I want to download these from within my app and store them in the apps 'Documents' folder. How can I do this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
最简单的方法是使用 NSData 的便捷方法
initWithContentOfURL:
和writeToFile:atomically:
分别获取数据并将其写出。请记住,这是同步的,并且会阻塞您执行它的任何线程,直到获取和写入完成。例如:
documentsDirectory
方法被无耻地从 这个问题:但是,除非您打算自己线程化它,否则这将在文件下载时停止 UI 活动。相反,您可能想查看 NSURLConnection 及其委托 - 它在后台下载并通知委托有关异步下载的数据,因此您可以构建 NSMutableData 的实例,然后在连接完成时将其写出。您的委托可能包含以下方法:
小细节,例如声明 dataAccumulator 和处理错误,留给读者:)
重要文档:
The easy way is to use NSData's convenience methods
initWithContentOfURL:
andwriteToFile:atomically:
to get the data and write it out, respectively. Keep in mind this is synchronous and will block whatever thread you execute it on until the fetch and write are complete.For example:
Where the
documentsDirectory
method is stolen shamelessly from this question:However, unless you intend to thread it yourself this will stop UI activity while the file downloads. You may instead want to look into NSURLConnection and its delegate - it downloads in the background and notifies a delegate about data downloaded asynchronously, so you can build up an instance of NSMutableData then just write it out when the connection's done. Your delegate might contain methods like:
The little details, like declaring the
dataAccumulator
and handling errors, are left to the reader :)The important documents: