Archive for février, 2009

Writing / Reading files on native Iphone Application

Here is a little sample to write/read files with objective c on native Iphone Application.
This snippet write into the Document Directory of the application. We will see later problems when trying to write in the Resources folder


WRITE

 NSString *dataStr = @"my data"; //get Document Root NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); NSString *documentsDirectory = [paths objectAtIndex:0]; //append file name to path NSString *filePath = [documentsDirectory stringByAppendingPathComponent:@"myFile"]; //prepar data in A NSData from a String NSData *aData = [dataStr dataUsingEncoding: NSUTF8StringEncoding]; //Write to the file. //File will be automacally created if not exist [aData writeToFile:filePath atomically:YES]; 



READ

 //get Document root NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); NSString *documentsDirectory = [paths objectAtIndex:0]; NSString *filePath = [documentsDirectory stringByAppendingPathComponent:@"myFile"]; NSString *myText = [NSString stringWithContentsOfFile:filePath]; if (myText) {     return myText; } else  {     //can not read because file does not exists     //make here your error handler } 





WARNING : It is possible to get a file from Resources Folder with the follwing line :

 NSString *filePath = [[NSBundle mainBundle] pathForResource:fileName ofType:extension]; 


Be carreful with that because if the file does not exist filePath will be null, so it will be impossible to create the file… difficult to write into the file :p