[ios] Write a file on iOS

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.

This question is related to ios iphone file nsbundle

The answer is


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];

}

Try making

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

as

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

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

Examples related to ios

Adding a UISegmentedControl to UITableView Crop image to specified size and picture location Undefined Symbols error when integrating Apptentive iOS SDK via Cocoapods Keep placeholder text in UITextField on input in IOS Accessing AppDelegate from framework? Autoresize View When SubViews are Added Warp \ bend effect on a UIView? Speech input for visually impaired users without the need to tap the screen make UITableViewCell selectable only while editing Xcode 12, building for iOS Simulator, but linking in object file built for iOS, for architecture arm64

Examples related to iphone

Detect if the device is iPhone X Xcode 8 shows error that provisioning profile doesn't include signing certificate Access files in /var/mobile/Containers/Data/Application without jailbreaking iPhone Certificate has either expired or has been revoked Missing Compliance in Status when I add built for internal testing in Test Flight.How to solve? cordova run with ios error .. Error code 65 for command: xcodebuild with args: "Could not find Developer Disk Image" Reason: no suitable image found iPad Multitasking support requires these orientations How to insert new cell into UITableView in Swift

Examples related to file

Gradle - Move a folder from ABC to XYZ Difference between opening a file in binary vs text Angular: How to download a file from HttpClient? Python error message io.UnsupportedOperation: not readable java.io.FileNotFoundException: class path resource cannot be opened because it does not exist Writing JSON object to a JSON file with fs.writeFileSync How to read/write files in .Net Core? How to write to a CSV line by line? Writing a dictionary to a text file? What are the pros and cons of parquet format compared to other formats?

Examples related to nsbundle

accessing a file using [NSBundle mainBundle] pathForResource: ofType:inDirectory: Write a file on iOS