How to find and read a file on iphone from objective C code, and to write a file

I am new... I have no idea what tag to select for this..

I have a file SeedFile.txt in the On My iPhone directory. I am trying to read it, and to write a different file out. To find it, I tried the following to get a path to the file, but I get a nil string.     NSString *filepath = [[NSBundle mainBundle] pathForResource:@"SeedFile" ofType:@"txt"];

Lines of obj c code to read this file and to write a myfile.txt would be appreciated.

The main bundle approach won’t help here; it’s for accessing files that are built in to your app’s bundle.

The On My iPhone area in Files maps to your Documents directory. To read a fixed item in that directory, use code like this:

NSError * error = nil;
NSURL * docDir = [NSFileManager.defaultManager URLForDirectory:NSDocumentDirectory inDomain:NSUserDomainMask appropriateForURL:nil create:true error:&error];
// … check that `docDir` is not `nil` and handle error otherwise …
NSURL * seedFile = [docDir URLByAppendingPathComponent:@"SeedFile.txt"];
NSString * seedText = [NSString stringWithContentsOfFile:seedFile encoding:NSUTF8StringEncoding error:&error];
// … check that `seedFile` is not `nil` and handle error otherwise …

IMPORTANT Most high-level APIs use file URLs rather than file paths, because URLs can carry extra information needed in various circumstances.

Share and Enjoy

Quinn “The Eskimo!” @ Developer Technical Support @ Apple
let myEmail = "eskimo" + "1" + "@" + "apple.com"

How to find and read a file on iphone from objective C code, and to write a file
 
 
Q