2

I used

NSURL *urlA = [info valueForKey:@"PHImageFileURLKey"];

but when i try to save image using URL then URL is nil.

NSData *pngData = [NSData dataWithContentsOfURL:urlA options:NSDataReadingMapped error:nil];
Iulian Onofrei
  • 9,188
  • 10
  • 67
  • 113
Keyur
  • 180
  • 1
  • 5
  • 20

3 Answers3

12

You can get the imageURL from PHContentEditingInput:

Swift:

asset.requestContentEditingInput(with: PHContentEditingInputRequestOptions()) { (eidtingInput, info) in
  if let input = eidtingInput, let imgURL = input.fullSizeImageURL {
     // imgURL 
  }
}

Objective-C:

[asset requestContentEditingInputWithOptions:[PHContentEditingInputRequestOptions new] completionHandler:^(PHContentEditingInput *contentEditingInput, NSDictionary *info) {
    NSURL *imageURL = contentEditingInput.fullSizeImageURL;
}];
a_tuo
  • 651
  • 7
  • 23
  • @a-tuo please answer in Objective-C becauase i have no idea in Swift – Keyur Jun 10 '17 at 10:57
  • @KeyurAspiration Have you add the "Privacy - Photo Library Usage Description" key in plist to get the permission of accessing Photos? – a_tuo Jun 10 '17 at 11:23
  • @a-tuo Yes, i already given this "Privacy - Photo Library Usage Description" – Keyur Jun 10 '17 at 11:27
  • Not working for me (iOS 14.4) PHImageFileURLKey not included in dictionary. – Ofir Malachi Feb 07 '21 at 16:05
  • 1
    The property of 'isNetworkAccessAllowed' needs to be set with true, if the image is not in local. See full code: ```let requestOptions = PHContentEditingInputRequestOptions() requestOptions.isNetworkAccessAllowed = true asset.requestContentEditingInput(with: requestOptions) { (editingInput, info) in }``` – Johnny Apr 25 '21 at 07:58
7

asset = Here you have to pass your PHAsset .

PHImageRequestOptions * imageRequestOptions = [[PHImageRequestOptions alloc] init];
 [[PHImageManager defaultManager]
             requestImageDataForAsset:asset
                            options:imageRequestOptions
                      resultHandler:^(NSData *imageData, NSString *dataUTI,
                                      UIImageOrientation orientation, 
                                      NSDictionary *info) 
     {
          NSLog(@"info = %@", info);
          if ([info objectForKey:@"PHImageFileURLKey"]) {

               NSURL *path = [info objectForKey:@"PHImageFileURLKey"];
               // if you want to save image in document see this.
               [self saveimageindocument:imageData withimagename:[NSString stringWithFormat:@"DEMO"]];
          }                                            
    }];

-(void) saveimageindocument:(NSData*) imageData withimagename:(NSString*)imagename{

    NSString *writePath = [NSString stringWithFormat:@"%@/%@.png",[Utility getDocumentDirectory],imagename];

    if (![imageData writeToFile:writePath atomically:YES]) {
        // failure
        NSLog(@"image save failed to path %@", writePath);

    } else {
        // success.
        NSLog(@"image save Successfully to path %@", writePath);
    }

}
+ (NSString*)getDocumentDirectory {
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    return [paths objectAtIndex:0];
}

Check image that landscape mode or portrait mode

if (chooseimage.size.height >= chooseimage.size.width)
{
         Islandscape = NO;
}else{
     UIImage* landscapeImage = [UIImage imageWithCGImage:chooseimage.CGImage
                                                      scale:chooseimage.scale
                                                orientation:UIImageOrientationLeft];
        self.imgPreviewView.image = landscapeImage;
        self.imgPreviewView.contentMode = UIViewContentModeScaleAspectFill;
        Islandscape = YES;
 }

Add this permission into info.plist file

<key>NSPhotoLibraryUsageDescription</key>
<string>$(PRODUCT_NAME) would like to access your photo library to let you select a picture.</string>
Himanshu Moradiya
  • 4,769
  • 4
  • 25
  • 49
  • Thanks for ans i tried your ans but i receive this type error print on log::setting security information: Operation not permitted and also I try to save image from Phasset URL to document Direcory , but I get The error - access not allow due to security reason. – Keyur Jun 10 '17 at 11:23
  • you have to add one thing in info.plist file that is i added in my answer. @KeyurAspiration – Himanshu Moradiya Jun 10 '17 at 11:32
  • i already added in info.plist like Photo,Camera,MicroPhone Description Access , one more thing ant other way array of images save into document directory with out memory warning issue.so please tell me. – Keyur Jun 10 '17 at 11:44
  • 1
    @KeyurAspiration check my updated answer that store image in document folder – Himanshu Moradiya Jun 10 '17 at 11:53
  • one more things can you help me?. I can get Image but portrait image shown in landscape. – Keyur Jun 12 '17 at 06:23
  • then write code for it landscape image to portraint – Himanshu Moradiya Jun 12 '17 at 06:28
  • @Himunshu-Moradiya thanks for last time reply one more thing i want your help for resolve my app crash issue show below link https://stackoverflow.com/questions/44778361/gatekeeperxpc-connection-to-assetsd-was-interrupted-or-assetsd-died-on-using-ima – Keyur Jun 27 '17 at 10:56
  • @KeyurAspiration in that question you have problem with image array that store value and when you process on image so its crush – Himanshu Moradiya Jun 28 '17 at 04:11
  • I know this problem occurs but how to handle it, can you describe? – Keyur Jun 28 '17 at 04:14
  • @KeyurAspiration the image you display is you getting from server throw any API ? – Himanshu Moradiya Jun 28 '17 at 04:29
  • 1
    Images not getting from a server it was picked from photo library using image picker library. – Keyur Jun 28 '17 at 04:39
  • imageRequestOptions is really necessary? maybe put nil does the same. – jose920405 Jan 04 '18 at 16:06
  • @jose920405 we have to pass imageRequestOptions Object in that method that why i create one instance first and then pass in method – Himanshu Moradiya Jan 05 '18 at 03:45
-1

//This is the Complete Swift Code of getting image URL with PHAsset answer of Himanshu Moradiya

  let imageRequestOptions = PHImageRequestOptions()
  PHImageManager.default().requestImageData(for: currentAsset, options: imageRequestOptions, resultHandler: { imageData, dataUTI, orientation, info in
    if let info = info {
      print("info = \(info)")
    }
    if info?["PHImageFileURLKey"] != nil {

      let path = info?["PHImageFileURLKey"] as? URL
       print(path) //here you get complete URL


      // if you want to save image in document see this.
     // self.saveimageindocument(imageData, withimagename: "DEMO")
    }
  })
Syed Haris
  • 21
  • 3