0

I have text file text.txt in my xcode project and I need to write NSString init from my iOS app. I've tried this code

NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *docDir = [paths objectAtIndex: 0];
NSString *docFile = [docDir stringByAppendingPathComponent: @"text.txt"];
NSString *content = @"Test";
[content writeToFile: docFile atomically: NO];

But it doesn't work for me... So can you help me with it?

stepik21
  • 2,610
  • 3
  • 22
  • 32
  • looks fine. I cant test now. Try removing `.txt`... – Anoop Vaidya Jun 30 '13 at 13:55
  • Look at stack's answer : http://stackoverflow.com/questions/5619719/write-a-file-on-ios – Anoop Vaidya Jun 30 '13 at 13:56
  • I don't know, what's wrong... I have text.txt in my Resources folder in Xcode and when I try to read it, it is ok, but when I want to write something new init, it doesn't work... :-( Have you any solution, please? – stepik21 Jun 30 '13 at 14:21

1 Answers1

0

this worked for me

//Method writes a string to a text file
-(void) writeToTextFile{
        //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:@"%@/text.txt", 
                                                      documentsDirectory];
        //create content - four lines of text
        NSString *content = @"Test";
        //save content to the documents directory
        [content writeToFile:fileName 
                         atomically:NO 
                               encoding:NSStringEncodingConversionAllowLossy 
                                      error:nil];

}
Agent Chocks.
  • 1,312
  • 8
  • 19
  • Do not build a path using `stringWithFormat:`. Append it properly using `NSString *filename = [documentsDirectory stringByAppendingPathComponent:@"text.txt"];` – rmaddy Jul 23 '14 at 22:27