UIImage imageWithContentsOfFile : not working on iOS8

标签 uiimage ios8 beta

当我在 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,因此,许多应用程序都使用bundle来组织资源,例如图像。但现在,这个漏洞会让成千上万的应用变得丑陋难用。我们真的希望苹果能在下一个版本中修复这个错误,否则我所有的应用程序都必须为这个错误开发一个新版本!

最佳答案

它实际上并没有损坏,您只是将其发送到错误的路径。
我猜您正在使用模拟器,并在您的应用程序中的某处保存了一个文件,然后记下了该文件的完整路径。但是,当您重建应用程序时,已安装应用程序的 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];

关于UIImage imageWithContentsOfFile : not working on iOS8,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25279239/

相关文章:

ios - 在 UIScrollView 问题中裁剪缩放图像

ios - 从 Bundle 加载图像我得到一个 nil

ios - 包含 UITableView 的 UITableViewCell 的高度(iOS8 和 AutoLayout)

ios - 使用百分比揭示 UIImageView

ios - 从 CMSampleBuffer 构建的 UIImage 未保留并导致 EXC_BAD_ACCESS

ios - UIView没有成员animateWithDuration?

swift - 如何在 didBeginContact 中删除 SKSpriteNode

Python pandas 使用滚动以矢量化方式应用于 groupby 对象来计算机车车辆 beta

.net - .Net 框架的早期历史是什么?

ios - Xcode 8 Beta 6 : storeViewController. 加载产品