【问题标题】:UIImage imageWithContentsOfFile: not working on iOS8UIImage imageWithContentsOfFile:不适用于 iOS8
【发布时间】:2014-10-06 09:42:07
【问题描述】:

当我在 iOS8 beta3 和 beta5 上测试我的应用时,我发现了一个关于 [UIImage imageWithContentsOfFile:] 的错误。

当图片资源存储在主包的子包中时,如果我们通过以下方法初始化 UIImage,它将返回 nil:

NSString *testBundlePath = [[NSBundle mainBundle] pathForResource:@"test" ofType:@"bundle”];
NSBundle *bundle = [NSBundle bundleWithPath:testBundlePath];
NSString *path = [bundle pathForResource:@"play.png" ofType:nil];

UIImage *image = [UIImage imageWithContentsOfFile:path]; //iOS8 image = nil, iOS7 image != nil

但是当图片资源存放在main bundle中时,UIImage初始化可以通过以下方法成功:

NSString *path = [[NSBundle mainBundle] pathForResource:@"play.png" ofType:nil];

UIImage *image = [UIImage imageWithContentsOfFile:path]; //iOS8 and iOS7 image != nil

我们在iOS8 beta3下发现了这个问题,在iOS8 beta 5下依然存在。

The Demo app directory structure was below:
      XXX.app
           |----test~ipad.bundle
                |----play.png
           |----test~iphone.bundle
                |----play.png
           |----play.png
           |----play~iphone.png
           |----play~ipad.png
         ......

有人有同样的问题吗?我认为这是iOS8上的一个bug,所以很多app都使用bundle来组织资源,比如图片。但现在,这个漏洞会让成千上万的应用变得丑陋且难以使用。我们真心希望苹果能在下个版本修复这个bug,否则我所有的应用都得为这个bug开发一个新版本!

【问题讨论】:

  • 你在这一行有问题 NSString *path = [bundle pathForResource:@"play.png" ofType:nil];将其更改为 NSString *path = [bundle pathForResource:@"play" ofType:"png"];或者你也可以试试 PNG
  • 感谢您的回答,但 NSString *path = [bundle pathForResource:@"play.png" ofType:nil] 在 iOS7 和 iOS8 上运行良好,并且 NSString *path = [bundle pathForResource:@" play" ofType:"png"] 也无法在 iOS8 上运行。:(

标签: uiimage ios8 beta


【解决方案1】:

pathForResource:ofType: 仅在资源文件夹(和本地化文件夹)中查找。如果要将文件放入捆绑包中的专用文件夹,则需要使用 pathForResource:ofType:inDirectory: 并提供目录名称。

【讨论】:

    【解决方案2】:

    实际上并没有损坏,只是您将其发送到错误的路径。 我猜您正在使用模拟器,并在您的应用程序中的某个位置保存了一个文件,然后记下了该文件的完整路径。但是,当您重建应用程序时,已安装应用程序的 UUID 会更改,并且您保存的路径不再有效(即使文件仍然存在)。您可以通过检查 [[NSFileManager defaultManager] currentDirectoryPath] 查看当前的活动路径。请注意,每次重新构建和重新部署应用时,该值都会发生变化。

    要获取您的实际文件,您需要执行以下操作:

    NSString *image = @"myImage.png";
    
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
    NSString *cache = [paths objectAtIndex:0];
    NSString *fullPath = [NSString stringWithFormat:@"%@/%@", cache, image];
    UIImage *image = [UIImage imageWithContentsOfFile:fullPath];
    

    【讨论】:

    • 感谢您的帮助 - 真烦人!
    【解决方案3】:

    Apple 已在 iOS8.1 上修复了此错误,干杯

    【讨论】:

      【解决方案4】:

      只需使用

      NSString *fullPath = [bundle pathForResource:name ofType:@"png"];
      NSData *data = [NSData dataWithContentsOfFile:fullPath];
      UIImage *image = [UIImage imageWithData:data];
      

      【讨论】:

        猜你喜欢
        • 2013-02-24
        • 1970-01-01
        • 1970-01-01
        • 2014-01-03
        • 1970-01-01
        • 1970-01-01
        • 2014-12-25
        • 1970-01-01
        • 2015-11-27
        相关资源
        最近更新 更多