简体   繁体   English

无法从iPhone文档目录位置中的已保存文件重新加载UIImage

[英]Can't Reload UIImage from Saved file in iPhone Documents Directory location

I am making an app that will save a file to the iPhones Documents Directory and then when the View Controller is reloaded it will fetch it from that same location and display it. 我正在制作一个将文件保存到iPhones文档目录的应用程序,然后在重新加载View Controller时,它将从同一位置获取文件并显示它。 But it is not fetching it and displaying it. 但是它不是获取并显示它。

I am using the following method to save the image: 我正在使用以下方法保存图像:

void UIImageWriteToFile(UIImage *image, NSString *fileName)
{
    NSArray *dirPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentDirectoryPath = dirPaths[0];
    NSString *filePath = [documentDirectoryPath stringByAppendingPathComponent:fileName];

    NSData *imageData = UIImagePNGRepresentation(image);
    [imageData writeToFile:filePath atomically:YES];
}

I am trying to recall the image I have saved from the viewDidLoad method with the following code: 我正在尝试使用以下代码调用从viewDidLoad方法保存的图像:

    NSArray *dirPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentDirectoryPath = dirPaths[0];

    NSString *fileName = [NSString stringWithFormat:@"/%@.png", self.fullname.text];

    NSString *filePath = [documentDirectoryPath stringByAppendingString:fileName];
    [self.imageView setImage:[UIImage imageNamed: filePath]];

However, it is not showing my image. 但是,它没有显示我的图像。 Can anyone help me and tell me where I am going wrong please. 谁能帮助我,告诉我我要去哪里了。 I am new to iOS Development. 我是iOS开发的新手。

replace this line: [self.imageView setImage:[UIImage imageNamed: filePath]]; 替换此行: [self.imageView setImage:[UIImage imageNamed: filePath]];

with this one : 与这个:

UIImage *image = [[UIImage alloc] initWithContentsOfFile:filePath];
[self.imageView setImage:image];

You can use [UIImage imageNamed:] with images from the Documents folder and have the benefits of the underlying caching mechanism, but the file path is slightly different. 您可以将[UIImage imageNamed:]与Documents文件夹中的图像一起使用,并具有底层缓存机制的优点,但是文件路径略有不同。

Use the following: 使用以下内容:

 NSString *fileName = [NSString stringWithFormat:@"../Documents/%@.png", self.fullname.text];
 UIImage *image = [UIImage imageNamed:fileName];

You need to use method 您需要使用方法

- (UIImage*)initWithContentsOfFile:(NSString*)path

to init images from Documents or Cache directories. 从文档或缓存目录初始化图像。

imageNamed: is used for getting images from application bundle. imageNamed:用于从应用程序捆绑包中获取图像。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM