Writing/reading to paths with interleaved double d

2019-08-28 18:25发布

问题:

This code fails on iOS 8, although it would work on iOS 7

UIImage *imageTest = ...

NSString *file = @"../Documents/Test.png";
NSString *fullpath = [[[NSBundle mainBundle] bundlePath] stringByAppendingPathComponent: file];

[UIImagePNGRepresentation(imageTest) writeToFile: fullpath atomically: YES];

UIImage *image = [UIImage imageNamed: file];

On iOS 8 I need to use this instead

NSString *file = [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0] stringByAppendingPathComponent:@"Test.png"];

[UIImagePNGRepresentation(imageTest) writeToFile:file atomically:YES];

UIImage *image = [[UIImage alloc] initWithContentsOfFile: file];

...but then I have to refactor my project and a third party library that works with paths relative to the main bundle.

It seems to me that paths like "/PathToMainBundle/MyApp.app/../Documents/something" are either not properly resolved, or not allowed at all by iOS 8

That path should be the same as "/PathToMainBundle/Documents/something"

回答1:

In iOS8, Resource Directory(App.app), Data Directory(NSCachesDirectory, NSTemporaryDirectory,..) are managed separately as below.

  • iOS7 Directory Hierarchy
    • App UUID
      • Documents
      • Library
        • Caches
        • Preferences
      • tmp
      • App.app
  • iOS8 Directory Hierarchy
    • Resource Directory UUID
      • App.app
    • Data Directory UUID
      • Documents
      • Library
        • Caches
        • Preferences
      • tmp

So, you should fix code based on absolute path in iOS8.

UIImage *imageTest = ...

NSString *fullpath = [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) firstObject] stringByAppendingPathComponent:@"Test.png"];

[UIImagePNGRepresentation(imageTest) writeToFile: fullpath atomically: YES];

UIImage *image = [UIImage imageNamed: fullpath];


标签: ios8 nsdata