Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

iOS: Saving into a file works on emulator but not on device

Tags:

file-io

ios

My app writes an encrypted data of the user info/preferences into a file, and reads from that file the next time the app is opened.

Writing a file:

- (BOOL)writeFile:(NSString *)data:(NSString *)fileName {
  return [data writeToFile:fileName
                atomically:YES
                  encoding:NSUTF8StringEncoding error:nil];
}

Reading a file:

- (NSString *)readFile:(NSString *)fileName {
  NSData *data = [NSData dataWithContentsOfFile:fileName];
  NSString *str = [[[NSString alloc] initWithData:data
                                         encoding:NSUTF8StringEncoding] autorelease];
  return str;
}

This works fine on the emulator. The files are written and read as expected. Is there anything I have to setup for file read/write on devices?

like image 705
dee Avatar asked Oct 18 '11 13:10

dee


1 Answers

The filename has to be in the documents directory. The simulator won't have as many restrictions on where it can write files as the device does.

Obtain the documents directory as follows:

NSString *documentsDirectory = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
NSString *fileName = [documentsDirectory stringByAppendingPathComponent:@"myfilename.extension"];

Pass this into your functions above and you should be fine.

like image 104
jrturton Avatar answered Nov 04 '22 01:11

jrturton