UIImage imageWithContentsOfFile: 在iOS8上无法正常工作

4

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

当图像资源存储在主包的子包中时,如果我们通过以下方法初始化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

但是当图像资源存储在主捆绑包中时,可以通过以下方法成功初始化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来组织资源,例如图像。但现在,这个bug会使成千上万的应用程序变得丑陋和难以使用。我们真的希望苹果公司能在下一个版本中修复这个bug,否则,我的所有应用程序都必须为这个bug开发一个新版本!


你在这一行代码NSString *path = [bundle pathForResource:@"play.png" ofType:nil]; 遇到了问题,将其更改为NSString *path = [bundle pathForResource:@"play" ofType:"png"]; 或者你也可以尝试使用PNG。 - Husrat Mehmood
谢谢您的回答,但是NSString *path = [bundle pathForResource:@"play.png" ofType:nil] 在iOS7和iOS8上都能正常工作,而NSString *path = [bundle pathForResource:@"play" ofType:"png"] 在iOS8上也无法工作。:( - Javan
4个回答

5

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

谢谢你的帮助 - 真烦人! - DiscDev

0

只需使用

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

0

苹果已经在iOS8.1上修复了这个漏洞,庆祝一下吧!


0

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


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接