从 URL 存储和加载文件

发布于 2024-10-25 05:19:35 字数 831 浏览 4 评论 0原文

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

岁月如刀 2024-11-01 05:19:36

您所拥有的内容看起来是正确的,要将该文件读回字符串,请使用:

编辑:(将usedEncoding更改为encoding)

NSError *error = nil;
NSString *fileContents = [NSString stringWithContentsOfFile:storePath encoding:NSUTF8StringEncoding error:&error];

当然,如果您使用特定的编码类型,则应该更改字符串编码类型,但UTF8可能是正确的。

What you have looks correct, to read that file back into a string use:

EDIT: (changed usedEncoding to encoding)

NSError *error = nil;
NSString *fileContents = [NSString stringWithContentsOfFile:storePath encoding:NSUTF8StringEncoding error:&error];

Of course you should change the string encoding type if you are using a specific encoding type, but UTF8 is likely correct.

故事还在继续 2024-11-01 05:19:36

如果您在主线程上执行此操作,那么不,这是不正确的。任何类型的网络连接都应该在后台完成,这样您就不会锁定界面。为此,您可以创建一个新线程(NSThreadperformSelectorInBackground: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).

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文