简体   繁体   中英

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

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM