将图像保存到 Documents 目录,然后将其加载到 UIImageView

Save image to Documents directory than load it into UIImageView

几天以来我一直在努力解决这个问题。我有一个应用程序,用户在其中选择一个图像,然后将所选图像保存到磁盘并稍后加载到 UIImageView 中,但是无论我尝试什么,这都不起作用。我做了一个小应用程序只是为了测试这个,但它在那里也不起作用。 imageView 保持空白。这是我的代码:

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (IBAction)button:(id)sender {
    UIImagePickerController *picker = [[UIImagePickerController alloc] init];
    picker.allowsEditing = NO;
    picker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
    [self presentViewController:picker animated:YES completion:nil];

}

-(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info{
    UIImage *selectedImage = info[UIImagePickerControllerOriginalImage];
    [self saveImage:selectedImage];
    self.imageView.image = [self loadImage];
    [picker dismissViewControllerAnimated:YES completion:NULL];

}

- (void)saveImage: (UIImage*)image
{
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,
                                                         NSUserDomainMask, YES);
    NSString *documentsDirectory = [paths objectAtIndex:0];
    NSString* path = [documentsDirectory stringByAppendingPathComponent:
                      @"image.png" ];
    NSData* data = UIImagePNGRepresentation(image);
    [data writeToFile:path atomically:YES];
}


- (UIImage*)loadImage
{
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,
                                                         NSUserDomainMask, YES);
    NSString *documentsDirectory = [paths objectAtIndex:0];
    NSString* path = [documentsDirectory stringByAppendingPathComponent:
                      @"image.png" ];
    UIImage* image = [UIImage imageWithContentsOfFile:path];
    return image;
}

@end

我做错了什么?

你只需要添加 UIImagePickerController 的委托,下面的代码就可以解决你的问题。

- (IBAction)button:(id)sender {
    UIImagePickerController *picker = [[UIImagePickerController alloc] init];
    picker.allowsEditing = NO;
    picker.delegate = self;
    picker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
    [self presentViewController:picker animated:YES completion:nil];
}

现在,在 .h 文件中使用以下代码。

#import <UIKit/UIKit.h>

@interface ViewController : UIViewController<UINavigationControllerDelegate,UIImagePickerControllerDelegate>
@property(nonatomic,weak)IBOutlet UIImageView *imageView;

@end