在ui图像查看器中上传的照片不断消失

时间:2019-01-31 00:25:52

标签: ios objective-c cocoa-touch

我可以从相机胶卷将照片上传到ui图像查看器中,但是当我重新启动应用程序或转到另一页面并返回时,上传的照片会消失。我如何保留它们?

 - (IBAction)selectImage:(id)sender {

UIImagePickerController *picker = [[UIImagePickerController alloc] init];
picker.delegate = self;
picker.allowsEditing = YES;
picker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;

[self presentViewController:picker animated:YES completion:NULL];

}

- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingImage:(UIImage *)selectedImage editingInfo:(NSDictionary *)editingInfo
{
UIImage *chosenImage = selectedImage;

self.homeImage.image = chosenImage;
[self.view setNeedsDisplay];

[picker dismissViewControllerAnimated:YES completion:NULL];

NSData *imageData = UIImagePNGRepresentation(chosenImage.images);
NSString *imagePath = [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0] stringByAppendingPathComponent:@"/myImage.png"];
[imageData writeToFile:imagePath atomically:YES];
}

我希望第二种方法可以将图像保留在内部数据库中并继续显示我上传的图像,但事实并非如此。

1 个答案:

答案 0 :(得分:0)

创建视图后,您需要从文件中加载图像并将其分配给视图,类似于:

- (void)viewDidLoad {
    NSString * imagePath = [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0] stringByAppendingPathComponent:@"/myImage.png"];
    self.homeImage.image = [UIImage imageWithContentsOfFile:imagePath];
}