web-dev-qa-db-fra.com

Enregistrement du fichier texte dans le répertoire des documents dans iOS 7

J'essaie d'enregistrer un fichier texte brut dans le répertoire Documents dans iOS 7. Voici mon 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);
}

Voici l'erreur que j'obtiens:

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"}

Je ne peux pas comprendre pourquoi j'obtiens cette erreur en cours d'exécution sur le simulateur. Cela fonctionne si j'utilise NSTemporaryDirectory ().

23
user2877212

À partir du modèle Xcode d'Apple:

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

Vous pouvez enregistrer comme ceci:

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

La réponse de Mundi dans Swift:

    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!
}
2
Syed Asad Ali
    -(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];

    }
1
casillas