关闭应用程序后保存图片

时间:2015-11-15 11:11:20

标签: ios objective-c

有一个简单的应用程序,在故事板上添加了UIImageView和按钮 按钮打开照片库,我选择一个图像,最终它出现在UIimaeView上 但是当我杀死应用程序时,快照没有保存怎么办?

这是我的代码:

-(IBAction)takePic:(id)sender {

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

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

-(void)imagePickerControllerDidCancel:(UIImagePickerController *)picker { 
    [picker dismissViewControllerAnimated:YES completion:nil];
}

-(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{

self.image.image=[info objectForKey:UIImagePickerControllerOriginalImage];

    [self dismissViewControllerAnimated:YES completion:nil];
}

2 个答案:

答案 0 :(得分:2)

确定。试试这个:

#import "ViewController.h"
@import AssetsLibrary;

@interface ViewController () <UIImagePickerControllerDelegate, UINavigationControllerDelegate>

@property (weak, nonatomic) IBOutlet UIImageView *imageView;
@property (strong, nonatomic) UIImagePickerController *picker;

@end

@implementation ViewController

- (void)viewDidLoad {
  [super viewDidLoad];

  NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
  NSURL *selectedImageURL = [NSURL URLWithString:[userDefaults objectForKey:@"selectedImageURL"]];
  if (selectedImageURL) {
    [self getImageFromAssetsAtURL:selectedImageURL completion:^(UIImage *image, NSError *error) {
      if (!error && image) {
        self.imageView.image = image;
      }
    }];
  }
}

- (IBAction)pickImage:(UIButton *)sender {
  [self presentViewController:self.picker animated:YES completion:nil];
}

- (UIImagePickerController *)picker {
  if (!_picker) {
    _picker = [UIImagePickerController new];
    _picker.delegate = self;
    _picker.sourceType = UIImagePickerControllerSourceTypeSavedPhotosAlbum;
  }
  return _picker;
}

- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info {
  UIImage *selectedImage = info[UIImagePickerControllerOriginalImage];
  NSURL *selectedImageURL = info[UIImagePickerControllerReferenceURL];

  // set image
  self.imageView.image = selectedImage;

  // save image url
  NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
  [userDefaults setObject:selectedImageURL.absoluteString forKey:@"selectedImageURL"];
  [userDefaults synchronize];

  // dismiss
  [self dismissViewControllerAnimated:YES completion:nil];
}

- (void)getImageFromAssetsAtURL:(NSURL *)imageURL completion:(void (^)(UIImage *, NSError *))completion {
  ALAssetsLibrary *library = [ALAssetsLibrary new];
  [library assetForURL:imageURL resultBlock:^(ALAsset *asset) {
    UIImage *image = [UIImage imageWithCGImage:[[asset defaultRepresentation] fullResolutionImage]];
    completion(image, nil);
  } failureBlock:^(NSError *error) {
    completion(nil, error);
  }];
}

@end

因为从iOS 9.0开始不推荐使用AssetsLibrary,您可以而且应该使用Photos框架。你必须导入它......

@import Photos;

并将getImageFromAssetsAtURL...方法更改为以下内容:

PHFetchResult *result = [PHAsset fetchAssetsWithALAssetURLs:@[imageURL] options:nil];
  if (result.count == 1) {
    PHAsset *asset = result.firstObject;
    [[PHImageManager defaultManager] requestImageDataForAsset:asset options:nil resultHandler:^(NSData * _Nullable imageData, NSString * _Nullable dataUTI, UIImageOrientation orientation, NSDictionary * _Nullable info) {
      UIImage *selectedImage = [UIImage imageWithData:imageData];
      completion(selectedImage, nil);
    }];
  } else {
    completion(nil, nil);
  }

答案 1 :(得分:0)

最后我使用了这段代码。

- (void)viewDidLoad {

[super viewDidLoad];

    [self loadDefaultImage];
}
-void)viewDidAppear:(BOOL)animated
{
    [self loadDefaultImage];
}
- (IBAction)TakePic:(id)sender {

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

    [self presentViewController:picker animated:YES completion:NULL];
}
-(void)imagePickerControllerDidCancel:(UIImagePickerController *)picker {
    [picker dismissViewControllerAnimated:YES completion:NULL];
}
-(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
        NSString *mediaType = info[UIImagePickerControllerMediaType];
        [self dismissViewControllerAnimated:YES completion:nil];

        if ([mediaType isEqualToString:(NSString *)kUTTypeImage]) {
            UIImage *image = info[UIImagePickerControllerOriginalImage];

            //append filename to document directory url
            NSURL *urlSave = [[self getDocumentsPathURL] URLByAppendingPathComponent:@"imagee"];

            //do something to previously taken image (in this case: delete it)
            if ([[NSFileManager defaultManager] fileExistsAtPath:urlSave.path]) {
                [[NSFileManager defaultManager] removeItemAtPath:urlSave.path error:nil];
            }

            //save image to document directory
            [UIImagePNGRepresentation(image) writeToFile:urlSave.path atomically:YES];

            //optional: save image to photo library
            UIImageWriteToSavedPhotosAlbum(image, nil, nil, nil);
        }
}
-(NSURL *)getDocumentsPathURL
{
    //document directory of app
    return [[NSFileManager defaultManager] URLForDirectory:NSDocumentDirectory inDomain:NSUserDomainMask appropriateForURL:nil create:YES error:nil];
}
-(void)loadDefaultImage
{
    NSURL *urlImage = [[self getDocumentsPathURL] URLByAppendingPathComponent:@"imagee"];
    if ([[NSFileManager defaultManager] fileExistsAtPath:urlImage.path]) {
        NSData *dataFile = [[NSFileManager defaultManager] contentsAtPath:urlImage.path];
        UIImage *image = [UIImage imageWithData:dataFile];

        [_imageView setImage:image];
    }
    else {
        NSLog(@"Image not found");
    }
}