从目录加载UIImage不再工作



在过去的5或6个月里,我一直在将图像保存到我在用户设备上的documents目录中创建的Photos文件夹中。然后,当用户进入特定屏幕时,照片将加载到imageView中,直到最近,这一直运行良好。

现在,图像不再显示在图像视图中,并且当使用URL打印图像宽度和高度时,即使URL没有更改,值也为零。

我正在使用以下代码在图像视图中显示图像。

outputImageView = [[UIImageView alloc] init];
    [outputImageView setFrame:originalImageViewSize];
    outputImageView.image = [UIImage imageWithData:[NSData dataWithContentsOfFile:photoURL]];
    NSLog(@"width %f, height %f", outputImageView.image.size.width, outputImageView.image.size.height);

照片URL如下所示:/Users/fernandosantos/Library/Developer/CoreSimulator/Devices/6F3FCE2A-F7F9-4F77-B66D-3DA2A25BE166/data/CContainers/data/Application/C3867EFA-6AA8-4B71-A856-DCF7F83DEFF/Documents/AUDIBURY/Photos/COMMTRCIAL CSRSignature--2014-10-13 10-49-16.jpg

感谢

在iOS8中,应用程序文档目录在每次运行时都会动态更改其名称。您必须从Appdelegate使用以下方法才能获得当前文档目录路径:

// Returns the URL to the application's Documents directory.
- (NSURL *)applicationDocumentsDirectory
{
    return [[[NSFileManager defaultManager] URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask] lastObject];
}

您应该只保存文件的相对路径,而不是完整路径。这种方法也适用于iOS7。

您可以使用iOS模拟器并检查完整路径是否确实不存在。

感谢所有回复建议的人。

我结合了每个人的建议,提出了这个对我有效的解决方案

//get the documents directory, in iOS 8 this is now dynamic everytime you run the app.
 NSString *documentsDirectory = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
//Create the CurrentPhotoURL by using the current documents directory and the appending the photo name which
//was created when saving the image originally.
NSString *currentPhotoURL = [[documentsDirectory stringByAppendingString:@"/"] stringByAppendingString:photoName];

由于我在documents目录中创建了一个名为Photos的新文件夹,因此photoName变量包含Photos文件夹的名称,然后是最初保存时图像的名称。

然后,我将photoName变量附加到当前文档目录,以获得该照片的完整目录路径。

这可能不是最好的解决方案,但这是我想出的,而且很有效。

如果其他人需要更多信息,请与我联系。

最新更新