Friday, February 19, 2016

NSSearchPathForDirectoriesInDomains - Read/Write a file in an iOS app

This example shows how to write a string to a storage file in an iOS app and then print the file content by reading. The app is built with Xcode 7.2.1 (Swift 2.1.1) and tested with the iPhone simulator. The generated text file is checked with Mac terminal commands.

1. The code:

let text = "The quick brown fox jumps over the lazy dog."
        
let file = "storage.txt"
        
if let paths : [String] = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.AllDomainsMask, true) {
    let path = paths[0].stringByAppendingString("/\(file)") #'/' character is required to locate in folder
            
    //Write
    try! text.writeToFile(path, atomically: false, encoding: NSUTF8StringEncoding)
            
    //Read
    let result = try! String(contentsOfFile: path, encoding: NSUTF8StringEncoding)
            
    print(path)    //Print the file directory
    print(result)  //Print the string in storage.txt
} else {
    print("Error")

}

2. Run the code with the simulator. The debug console result is:


/Users/xxx/Library/Developer/CoreSimulator/Devices/06....5A/data/Containers/Data/Application/D7....D8/Documents/storage.txt

The quick brown fox jumps over the lazy dog.

3. Open terminal and go to the directory shown in the debug console.

cd /Users/xxx/Library/Developer/CoreSimulator/Devices/06....5A/data/Containers/Data/Application/D7....D8/Documents/

4. Check the file with the nano command:

nano storage.txt


Related information:

Read/Write a file in Python

iOS: Store data in plist with NSFileManager

No comments:

Post a Comment