Bogdan
Bogdan

Reputation: 863

Saving image to Photo Library and get the URL of the saved image

I'm trying to save an image from camera to Photo Library and then store the URL of the saved image. My code:

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

ALAssetsLibrary *library = [[ALAssetsLibrary alloc]init];
[library writeImageToSavedPhotosAlbum:(__bridge CGImageRef)([info objectForKey:UIImagePickerControllerOriginalImage])
                          orientation:ALAssetOrientationUp completionBlock:^(NSURL *assetURL, NSError *error) {
                              if(error == nil) {
                                  _myImageUrl = [NSString stringWithFormat:@"%@",assetURL];
                                  NSLog(@"%@",assetURL);
                              } else NSLog(@"%@",error);
                          }];

[picker dismissViewControllerAnimated:YES completion:nil];}

My problem is that assetUrl is always NULL. Any ideas? Thank you!

Upvotes: 4

Views: 1839

Answers (1)

Bogdan
Bogdan

Reputation: 863

Finally, after reading more, I found out the answer: the first parameter of the function is of CGImageRef type and (__bridge CGImageRef) doesn't do what I expected; but if I call the CGImage method of UIImage object, it works. The correct way to do this is:

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

    ALAssetsLibrary *library = [[ALAssetsLibrary alloc]init];
    CGImageRef image = [[info objectForKey:UIImagePickerControllerOriginalImage] CGImage];
    [library writeImageToSavedPhotosAlbum:image
                              orientation:ALAssetOrientationUp
                          completionBlock:^(NSURL *assetURL, NSError *error) {
                                  if(error == nil) {
                                      _myImageUrl = [NSString stringWithFormat:@"%@",assetURL];
                                      NSLog(@"%@",assetURL);
                                  } else NSLog(@"%@",error);
                              }];

    self.toDoImage.image = [info objectForKey:UIImagePickerControllerOriginalImage];
    [picker dismissViewControllerAnimated:YES completion:nil];
}

Upvotes: 1

Related Questions