简体   繁体   English

关闭应用程序后,从相机拍摄的照片不会出现在图像视图中

[英]A photo taken from the camera does not appear on the imageview after closing the application

I have two, my view on the. 我有两个,对我的看法。 1. imageview - img 2. Uibutton -takepic The aim of the app is to display an image on the ImageView. 1. imageview-img 2. Uibutton -takepic该应用程序的目的是在ImageView上显示图像。 When I click the button I have two options. 当我单击按钮时,有两个选项。 Or take a photo album, or take a photo camera. 或拍摄相册或相机。 When I take a picture from the album, the image is saved in my application and listed on the imageview and when I close the app that will run in the background and returning to the app, the image persists. 当我从相册中拍摄照片时,该图像将保存在我的应用程序中并在imageview中列出,而当我关闭将在后台运行的应用程序并返回该应用程序时,该图像仍然存在。 The problem is the camera, I take a picture when the camera is listed on the imageview and saved in the device's photo album. 问题是相机,当相机在imageview上列出并保存在设备的相册中时,我会拍照。 But when I close the app that will run in the background, and returns to the app, the image does not resides on the imageview Why? 但是,当我关闭将在后台运行的应用程序并返回到该应用程序时,图像不驻留在imageview上为什么?

It's my complete code: 这是我完整的代码:

-(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.img.image = image;
             }
         }];
    }
    // Creating a Circular Profile Image.
    self.img.layer.cornerRadius = self.img.frame.size.width / 2.0;
    self.img.clipsToBounds = YES;

    // Adding Border to image.
    self.img.layer.borderWidth = 6.0;
    self.img.layer.borderColor = [UIColor blackColor].CGColor;
}

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

-(IBAction)takePic:(id)sender {

    // ALERT SHEET.
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleActionSheet];

    //CAMERA
    UIAlertAction *openCamrea = [UIAlertAction actionWithTitle:@"צלם" style:UIAlertActionStyleDefault handler:^(UIAlertAction * action)
    {
        // If device has no camera.
        if (![UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera])
        {
            UIAlertController *alertNoCamera = [UIAlertController alertControllerWithTitle:@"Error" message:@"Device has no camera" preferredStyle:UIAlertControllerStyleAlert];
            UIAlertAction *ok = [UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleDefault handler:^(UIAlertAction * action){}];
            [alertNoCamera addAction:ok];
            [self presentViewController:alertNoCamera animated:YES completion:nil];
        }
        else// if  have a camera.
        {
           UIImagePickerController *picker = [[UIImagePickerController alloc] init];
           picker.delegate = self;
           picker.allowsEditing = YES;
           picker.sourceType = UIImagePickerControllerSourceTypeCamera;


           [self presentViewController:picker animated:YES completion:NULL];
        }
    }];
    // GALLERY
    UIAlertAction *openGallery = [UIAlertAction actionWithTitle:@"גלריה" style:UIAlertActionStyleDefault handler:^(UIAlertAction * action)
    {
        UIImagePickerController *picker = [[UIImagePickerController alloc] init];
        picker.delegate = self;
        picker.allowsEditing = YES;
        picker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;

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

    [alert addAction:openCamrea];
    [alert addAction:openGallery];

    [self presentViewController:alert animated:YES completion:nil];
}


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

    if(picker.sourceType == UIImagePickerControllerSourceTypeCamera)
    {
        UIImageWriteToSavedPhotosAlbum(image, self, @selector(image:didFinishSavingWithError:contextInfo:), nil);
        // set image
        self.img.image = image;
    }
    else{
        self.img.image = image;
    }
    // save image url
    NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
    [userDefaults setObject:selectedImageURL.absoluteString forKey:@"selectedImageURL"];
    [userDefaults synchronize];

    // set image
    self.img.image = image;

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

}
-(void)imagePickerControllerDidCancel:(UIImagePickerController *)picker {
    [picker dismissViewControllerAnimated:YES completion:NULL];
}
// chkeing if image save on album ot not.
- (void)image:(UIImage *)image didFinishSavingWithError:(NSError *)error contextInfo:(void *)contextInfo
{
    UIAlertAction *ok = [UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleDefault handler:^(UIAlertAction * action){}];
    if (error) // Unable to save the image
    {
        UIAlertController *alertErorr = [UIAlertController alertControllerWithTitle:@"Erorr" message:@"Unable to save image to Photo Album." preferredStyle:UIAlertControllerStyleAlert];
        [alertErorr addAction:ok];
        [self presentViewController:alertErorr animated:YES completion:nil];
    }
    else // All is well
    {
        UIAlertController *alertSuccess = [UIAlertController alertControllerWithTitle:@"Success" message:@"Image saved to Photo Album." preferredStyle:UIAlertControllerStyleAlert];
        [alertSuccess addAction:ok];

        self.img.image=image;
        [self presentViewController:alertSuccess animated:YES completion:nil];
    }
    [self dismissViewControllerAnimated:YES completion:NULL];
}
-(void)getImageFromAssetsAtURL:(NSURL *)imageURL completion:(void (^) (UIImage *, NSError *))completion
{
    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);
    }
}

@end

Best way will be saving the image to your app sandbox ( Document Directory ). 最好的方法是将图像保存到应用程序沙箱(“ Document Directory )中。 Normally I do not suggest saving image in NSUserDefaults , as NSUserDefaults should be used to store small settings but not raw image data. 通常我不建议将图像保存在NSUserDefaults ,因为NSUserDefaults应该用于存储小的设置,而不是原始图像数据。

When you have the image ready, save it in the app document folder. 准备好图像后,将其保存在应用程序文档文件夹中。 You can later remove the image from the saved path!!! 您以后可以从保存的路径中删除图像!!!

You can store the image path in the NSUserDefaults but not image!!! 您可以将图像路径存储在NSUserDefaults但不能存储图像!

To save the image: 要保存图像:

Put this code in didFinishPickingMediaWithInfo method: 将此代码放入didFinishPickingMediaWithInfo方法中:

If the image is in UIImageJPEGRepresentation use .jpeg extension, if it is in UIImagePNGRepresentation use .png extension 如果图像在UIImageJPEGRepresentation使用.jpeg扩展名;如果图像在UIImagePNGRepresentation使用.png扩展名

NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *filePath = [NSString stringWithFormat:@"%@/%@", documentsDirectory, @"myImage.png"];
NSLog(@"filePath %@", filePath);
    NSError *error;
[image writeToFile:filePath atomically:NO];

To get back the image: 取回图像:

    NSArray *arrayPaths =
    NSSearchPathForDirectoriesInDomains(
                                        NSDocumentDirectory,
                                        NSUserDomainMask,
                                        YES);
    NSString *path = [arrayPaths objectAtIndex:0];
    NSString* fileName = [path stringByAppendingPathComponent:@"myImage.png"];

  UIImage *image=[UIImage imageWithContentsOfFile:fileName];

library pictures are saved pictures but when you take picture from camera for your app then this will not be saved any where... so it will be deleted when app goes in back ground .... first save image anywhere.... fast method is save it to NSUserDefaults like this: 库图片是已保存的图片,但是当您从相机为应用程序拍摄照片时,它将不会被保存在任何位置...因此当应用程序进入背景时它将被删除....首先将图像保存在任何地方....快速方法将其保存到NSUserDefaults如下所示:

[NSUserdefaults standardUserDefaults] setObject:YourImage forkey:"myImage"];

after this when u came to foreground then in you viewWillAppear method u can set your image like this 之后,当您来到前台时,在您的viewWillAppear方法中,您可以像这样设置图像

yourImageView.image = [NSUserDefaults standardUserDefaults] ObjectForKey:"myImage"];

Thats all..Good luck 就是这样..祝你好运

Try this.. 尝试这个..

Take a "Strong" Property for "UIImage" say "myImage" and then assign it the image captured from the camera. 对“ UIImage”使用“强”属性,说“ myImage”,然后为其分配从相机捕获的图像。

Now use the "myImage" when assigning image to imageView. 现在将图像分配给imageView时使用“ myImage”。

暂无
暂无

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

相关问题 异步加载从UIImagePickerController相机拍摄的照片 - Loading a photo taken from UIImagePickerController camera asynchronously 在表格视图中显示从相机拍摄的照片 - Display a photo taken from camera in a table view 如何检测照片是否来自前置摄像头 - How to detect if photo taken from front camera 是否可以检查图像是由相机拍摄的还是由JavaScript从照片库上传的? - Is it possible to check if an image is taken by camera or uploaded from photo library by JavaScript? 如何编辑直接从相机拍摄的照片并将其上传到 iphone? - How to edit photo directly taken from camera and upload it on iphone? 如何检测照片库中的图像是由iPhone相机拍摄还是导入 - how to detect if image from photo library was taken by iPhone camera or imported 只有在相机拍摄时才将图像保存到照片库,如果从照片库中选择则不能 - Save images to photo library ONLY if they are taken by camera and not if chosen from photo library iOS上的MLKit文本检测适用于从Assets.xcassets拍摄的照片,但不适用于在相机上拍摄的同一照片/从相机胶卷上传的照片 - MLKit Text detection on iOS working for photos taken from Assets.xcassets, but not the same photo taken on camera/uploaded from camera roll 在iOS 7中旋转相机和拍摄的照片问题 - Rotating camera and photo taken issue in iOS 7 仅在用相机拍摄时如何保存照片? - How to save photo only when taken with camera?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM