Write a file on iOS

138,963

Solution 1

Your code is working at my end, i have just tested it. Where are you checking your changes? Use Documents directory path. To get path -

NSLog(@"%@",documentsDirectory);

and copy path from console and then open finder and press Cmd+shift+g and paste path here and then open your file

Solution 2

May be this is useful to you.

//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:@"%@/textfile.txt", 
                                                      documentsDirectory];
        //create content - four lines of text
        NSString *content = @"One\nTwo\nThree\nFour\nFive";
        //save content to the documents directory
        [content writeToFile:fileName 
                         atomically:NO 
                               encoding:NSUTF8StringEncoding 
                                      error:nil];

}


//Method retrieves content from documents directory and
//displays it in an alert
-(void) displayContent{
        //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];
        NSString *content = [[NSString alloc] initWithContentsOfFile:fileName
                                                      usedEncoding:nil
                                                             error:nil];
        //use simple alert from my library (see previous post for details)
        [ASFunctions alert:content];
        [content release];

}

Solution 3

Swift

func saveFile() {
    let paths = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)
    let documentsDirectory = paths[0] as! String
    let fileName = "\(documentsDirectory)/textFile.txt"
    let content = "Hello World"
    content.writeToFile(fileName, atomically: false, encoding: NSUTF8StringEncoding, error: nil)
}

func loadFile() {
    let paths = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)
    let documentsDirectory = paths[0] as! String
    let fileName = "\(documentsDirectory)/textFile.txt"
    let content: String = String(contentsOfFile: fileName, encoding: NSUTF8StringEncoding, error: nil)!
    println(content)
}

Swift 2

func saveFile() {
    let paths = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)
    let documentsDirectory = paths[0]
    let fileName = "\(documentsDirectory)/textFile.txt"
    let content = "Hello World"
    do{
        try content.writeToFile(fileName, atomically: false, encoding: NSUTF8StringEncoding)
    }catch _ {

    }

}

func loadFile()->String {
    let paths = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)
    let documentsDirectory = paths[0] 
    let fileName = "\(documentsDirectory)/textFile.txt"
    let content: String
    do{
       content = try String(contentsOfFile: fileName, encoding: NSUTF8StringEncoding)
    }catch _{
        content=""
    }
    return content;
}

Swift 3

func saveFile() {
    let paths = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)
    let documentsDirectory = paths[0]
    let fileName = "\(documentsDirectory)/textFile.txt"
    let content = "Hello World"
    do{
        try content.write(toFile: fileName, atomically: false, encoding: String.Encoding.utf8)
    }catch _ {

    }

}

func loadFile()->String {
    let paths = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)
    let documentsDirectory = paths[0]
    let fileName = "\(documentsDirectory)/textFile.txt"
    let content: String
    do{
        content = try String(contentsOfFile: fileName, encoding: String.Encoding.utf8)
    } catch _{
        content=""
    }
    return content;
}

Solution 4

Try making

NSString *appFile = [documentsDirectory stringByAppendingPathComponent:@"MyFile"];

as

NSString *appFile = [documentsDirectory stringByAppendingPathComponent:@"MyFile.txt"];
Share:
138,963

Related videos on Youtube

Riccardo Queri
Author by

Riccardo Queri

Updated on July 05, 2022

Comments

  • Riccardo Queri
    Riccardo Queri almost 2 years

    How do I write a file on iOS? I'm trying to do it with the following code but I'm doing something wrong:

    char *saves = "abcd";
    NSData *data = [[NSData alloc] initWithBytes:saves length:4]; 
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsDirectory = [paths objectAtIndex:0];
    NSString *appFile = [documentsDirectory stringByAppendingPathComponent:@"MyFile"];
    [data writeToFile:appFile atomically:YES];
    

    I have created MyFile.txt on resources.

    • Shaggy Frog
      Shaggy Frog about 13 years
      Please describe exactly what is going wrong.
  • Riccardo Queri
    Riccardo Queri about 13 years
    I cannot find the file where i write it seems it doesnt exist
  • Riccardo Queri
    Riccardo Queri about 13 years
    I guess this is where i'm wrong.. I have created MyFile inside my resource app directory.. Bu there arent changes there.. Where do I got to check or create the file?
  • Chetan Bhalara
    Chetan Bhalara about 13 years
    You can change the document directory path.
  • Chetan Bhalara
    Chetan Bhalara about 13 years
    use -- #define DOCUMENTS_FOLDER [NSHomeDirectory() stringByAppendingPathComponent:@"Documents"]
  • Riccardo Queri
    Riccardo Queri about 13 years
    if i dont do this wich is the default directory for my files?
  • Juan Munhoes Junior
    Juan Munhoes Junior over 11 years
    dont forget the command [[NSUserDefaults standardUserDefaults] synchronize]; after save..
  • Chetan Bhalara
    Chetan Bhalara over 11 years
    @JuanMunhoesJunior : I have not used NSUseDefaults in this code, Then why I write it.
  • Ron
    Ron almost 11 years
    What is NSStringEncodingConversionAllowLossy? Should the encoding be: NSUTF8StringEncoding instead?
  • Joshua Gross
    Joshua Gross over 10 years
    @Ron I made the edit, NSUTF8StringEncoding is required here.
  • auspicious99
    auspicious99 over 6 years
    @Ron Yes, with NSStringEncodingConversionAllowLossy, it gives a write error (these days with Xcode 9, iOS 11, etc.), the error being "The file couldn’t be saved using the specified text encoding."