Does an iOS app have write access inside its bundle?

后端 未结 2 399
逝去的感伤
逝去的感伤 2020-11-27 07:34

I save some run-time generated files inside the .app bundle of my iOS app. In the simulator it works fine, in the device it crashes:

Could create outp

相关标签:
2条回答
  • 2020-11-27 08:03

    The bundle is read-only. You don't want to mess around with it for two reasons:

    • Code Signing: the signature is verified by against the contents of the bundle; if you mess around with the bundle, you break the signature.
    • App Updates: updates work by replacing the entire app bundle with a newly downloaded one; any changes you make will get lost.

    Where you should save stuff:

    • Documents: if you want it to persist and be backed up
    • Library/Caches: if you just want to cache downloaded data, like profile pics; will be auto deleted by the system if it is low on room unless you specify with a special do-not-delete flag.
    • tmp: temporary files, deleted when your app is not running

    For a full explanation check out File System Programming Guide and QA1719.

    0 讨论(0)
  • 2020-11-27 08:05

    No, every time you change your bundle you invalidate your signature.

    If you want to write files you`l need to write in the best folder depending on what you want to do with that file.

    1. Documents folder for long duration files
    2. Cache for small operations
    3. and so on

    EDIT

    To get the path you`ll need something like this:

    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsDirectory = [paths objectAtIndex:0];
    NSString *path = [documentsDirectory stringByAppendingPathComponent:@"filename.ext"];
    

    With this path you can write or read like this:

    write:

    NSString *content = @"One\nTwo\nThree\nFour\nFive";
    [content writeToFile:fileName atomically:NO encoding:NSStringEncodingConversionAllowLossy error:nil];
    

    read:

    NSString *content = [[NSString alloc] initWithContentsOfFile:fileName usedEncoding:nil error:nil];
    
    0 讨论(0)
提交回复
热议问题