Writing/reading to paths with interleaved double dots fails on iOS 8

筅森魡賤 提交于 2019-12-13 04:59: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];


来源:https://stackoverflow.com/questions/25989767/writing-reading-to-paths-with-interleaved-double-dots-fails-on-ios-8

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!