I am reading a file in iphone app. Its Works Fine.
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSLog(@"%@",documentsDirectory);
NSString *fileName = [NSString stringWithFormat:@"%@/test.txt",documentsDirectory];
NSLog(@"%@",fileName);
NSString *content = [[NSString alloc] initWithContentsOfFile:fileName
usedEncoding:nil
error:nil];
NSLog (@"%@",content);
}
works good when i am using filename as test.txt
But when i add another file in the resource suppose test1.txt then NSLog(@"%@",documentsDirectory) and NSLog(@"%@",fileName) shows the right result. But
NSLog (@"%@",content); prints null in the log. So what is the reason?
I am printing detail error and it prints
NSFilePath = "/Users/sam-xxx/Library/Application Support/iPhone Simulator/3.2/Applications/51197946-6042-4A90-AA39-F07F8A649308/Documents/test1.txt";
NSUnderlyingError = Error Domain=NSPOSIXErrorDomain Code=2 "Operation could not be completed. No such file or directory";
It would be best here to check to see if an error is returned:
That will (hopefully) give you a clue as to whats going on.
(Edited to give example bundle resource usage as the file is in the bundle not the Documents directory).
Docs for NSBundle are here: NSBundle Documentation
You have 2 choices, the one you suggest:
Which will return the Bundle resource directory with the filename appended to that path.
Personally I prefer the pathForResource:ofType: method:
As this will not only tell you if the file exists (returns nil if it does not) but will also search the localisation directories if you have them.