从 URL 存储和加载文件
iPhone 应用程序
我目前正在尝试了解如何将文件从 URL 存储到文档目录,然后从文档目录中读取该文件。
NSURL *url = [NSURL URLWithString:@"http://some.website.com/file"];
NSData *data = [NSData dataWithContentsOfURL:url];
NSString *applicationDocumentsDir = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
NSString *storePath = [applicationDocumentsDir stringByAppendingPathComponent:@"Timetable.ics"];
[data writeToFile:storePath atomically:TRUE];
我从 http://swatiardeshna.blogspot.com/2010/06/how -to-save-file-to-iphone-documents.html
我想知道这是否是正确的方法,我想知道如何加载 将文件从文档目录转换为 NSString..
任何帮助将不胜感激。
iPhone App
I am currently trying to understand how i can store a file from a URL to the documents directory and then read the file from the documents directory..
NSURL *url = [NSURL URLWithString:@"http://some.website.com/file"];
NSData *data = [NSData dataWithContentsOfURL:url];
NSString *applicationDocumentsDir = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
NSString *storePath = [applicationDocumentsDir stringByAppendingPathComponent:@"Timetable.ics"];
[data writeToFile:storePath atomically:TRUE];
I got this code from http://swatiardeshna.blogspot.com/2010/06/how-to-save-file-to-iphone-documents.html
I want to know if this is the correct way to do this and i want to know how i can load the file from the documents directory into an NSString..
Any help will be greatly appreciated.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您所拥有的内容看起来是正确的,要将该文件读回字符串,请使用:
编辑:(将usedEncoding更改为encoding)
当然,如果您使用特定的编码类型,则应该更改字符串编码类型,但UTF8可能是正确的。
What you have looks correct, to read that file back into a string use:
EDIT: (changed usedEncoding to encoding)
Of course you should change the string encoding type if you are using a specific encoding type, but UTF8 is likely correct.
如果您在主线程上执行此操作,那么不,这是不正确的。任何类型的网络连接都应该在后台完成,这样您就不会锁定界面。为此,您可以创建一个新线程(
NSThread
、performSelectorInBackground:
、NSOperation
+NSOperationQueue
)或对其进行调度在运行循环(NSURLConnection
)上。If you're doing this on your main thread, then no it's not correct. Any sort of network connection should be done in the background so you don't lock up the interface. For that, you can create a new thread (
NSThread
,performSelectorInBackground:
,NSOperation
+NSOperationQueue
) or schedule it on the run loop (NSURLConnection
).