简体   繁体   中英

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. 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:

    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.

replace this line: [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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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