IOS 7のドキュメントディレクトリにプレーンテキストファイルを保存しようとしています。ここに私のコードがあります。
//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()を使用する場合に機能します。
AppleのXcodeテンプレートから:
/**
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];
SwiftでのMundiの答え:
let fileName = "/File Name.txt"
let filePath = self.applicationDocumentsDirectory().path?.stringByAppendingString(fileName)
do {
try strFileContents.writeToFile(filePath!, atomically: true, encoding: NSUTF8StringEncoding)
print(filePath)
}
catch {
// error saving file
}
func applicationDocumentsDirectory() -> NSURL {
return NSFileManager.defaultManager().URLsForDirectory(NSSearchPathDirectory.DocumentDirectory, inDomains: NSSearchPathDomainMask.UserDomainMask).last!
}
-(void)writeATEndOfFile:(NSString *)content2
{
NSArray *paths = NSSearchPathForDirectoriesInDomains
(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
//make a file name to write the data to using the documents directory:
NSString *fileName = [NSString stringWithFormat:@"%@/textfile.txt",
documentsDirectory];
if([[NSFileManager defaultManager] fileExistsAtPath:fileName])
{
NSFileHandle *fileHandle = [NSFileHandle fileHandleForWritingAtPath:fileName];
[fileHandle seekToEndOfFile];
NSString *writedStr = [[NSString alloc]initWithContentsOfFile:fileName encoding:NSUTF8StringEncoding error:nil];
content2 = [content2 stringByAppendingString:@"\n"];
writedStr = [writedStr stringByAppendingString:content2];
[writedStr writeToFile:fileName
atomically:NO
encoding:NSStringEncodingConversionAllowLossy
error:nil];
}
else {
int n = [content2 intValue];
[self writeToTextFile:n];
}
}
-(void) writeToTextFile:(int) value{
//get the documents directory:
NSArray *paths = NSSearchPathForDirectoriesInDomains
(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
//make a file name to write the data to using the documents directory:
NSString *fileName = [NSString stringWithFormat:@"%@/textfile.txt",
documentsDirectory];
//create content - four lines of text
// NSString *content = @"One\nTwo\nThree\nFour\nFive";
NSString *content2 = [NSString stringWithFormat:@"%d",value];
content = [content2 stringByAppendingString:@"\n"];
//save content to the documents directory
[content writeToFile:fileName
atomically:NO
encoding:NSStringEncodingConversionAllowLossy
error:nil];
}