将文本文件保存到iOS 7中的文档目录 [英] Saving text file to documents directory in iOS 7

查看:302
本文介绍了将文本文件保存到iOS 7中的文档目录的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将纯文本文件保存到iOS 7中的Documents目录。这是我的代码:

I am trying to save a plain text file to the Documents directory in iOS 7. Here is my code:

//Saving file
NSFileManager *fileManager = [[NSFileManager alloc] init];
NSArray *urls = [fileManager URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask];

NSString *url = [NSString stringWithFormat:@"%@", urls[0]];

NSString *someText = @"Random Text To Be Saved";
NSString *destination = [url stringByAppendingPathComponent:@"File.txt"];

NSError *error = nil;

BOOL succeeded = [someText writeToFile:destination atomically:YES encoding:NSUTF8StringEncoding error:&error];

if (succeeded) {
    NSLog(@"Success at: %@",destination);
} else {
    NSLog(@"Failed to store. Error: %@",error);
}

这是我得到的错误:

2013-10-13 16:09:13.848 SavingFileTest[13675:a0b] Failed to store. Error: Error Domain=NSCocoaErrorDomain Code=4 "The operation couldn’t be completed. (Cocoa error 4.)" UserInfo=0x1090895f0 {NSFilePath=file:/Users/Username/Library/Application%20Support/iPhone%20Simulator/7.0-64/Applications/F5DA3E33-80F7-439B-A9AF-E8C7FC4E1630/Documents/File.txt, NSUserStringVariant=Folder, NSUnderlyingError=0x10902aeb0 "The operation couldn’t be completed. No such file or directory"}

我无法弄清楚为什么我在模拟器上运行此错误。如果我使用NSTemporaryDirectory(),这是有效的。

I can't figure out why I am getting this error running on the simulator. This works if I use the NSTemporaryDirectory().

推荐答案

来自Apple的Xcode模板:

From Apple's Xcode Template:

/**
 Returns the URL to the application's Documents directory.
 */
- (NSURL *)applicationDocumentsDirectory {
    return [[[NSFileManager defaultManager] URLsForDirectory:NSDocumentDirectory 
         inDomains:NSUserDomainMask] lastObject];
}

您可以像这样保存:

NSString *path = [[self applicationDocumentsDirectory].path 
                       stringByAppendingPathComponent:@"fileName.txt"];
[sampleText writeToFile:path atomically:YES
                       encoding:NSUTF8StringEncoding error:nil];

这篇关于将文本文件保存到iOS 7中的文档目录的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆