Ethan_AI
Ethan_AI

Reputation: 1049

Read from URL obtained from PHImageFileURLKey

The Photo Framework for iOS 8 is able to return a URL for images using the PHImageFileURLKey. However I can't seem to read this URL. I only need read access. So far, any place I attempt to use the URL given, it is treated as though the file doesn't exist at all. How can I get data using the URL?

Code that successfully returns PHAssets and a URL:

PHFetchResult* phFetchResult = [PHAsset fetchAssetsWithMediaType:PHAssetMediaTypeImage options:nil]
PHImageManager *manager = [PHImageManager defaultManager];
PHImageRequestOptions* options = [[PHImageRequestOptions alloc] init];
options.synchronous = YES; // Force sequential work. We have nothing to do until this block returns.
PHAsset* asset = [phFetchResult objectAtIndex:index];
[manager requestImageForAsset:asset targetSize:PHImageManagerMaximumSize contentMode:PHImageContentModeDefault options:options resultHandler:^(UIImage *resultImage, NSDictionary *info)
 {
     _image = resultImage;
     NSURL* fileURL = [info objectForKey:@"PHImageFileURLKey"];
     _imageLocation = [fileURL relativePath];
 }];

Code showing nothing found:

NSURL* fileURL = [info objectForKey:@"PHImageFileURLKey"];
NSLog(@"File exist?: %d", [[NSFileManager defaultManager] fileExistsAtPath:[fileURL relativePath]]);

My current workaround is to take the UIImage given and save it to the /tmp directory and then use that URL. It's not an ideal solution and I'd really like to know the purpose of the PHImageFileURLKey

Upvotes: 4

Views: 4242

Answers (1)

SmarterSusheel
SmarterSusheel

Reputation: 169

I research on PHImageFileURLKey and i think there is no way to find image data by PHImageFileURLKey but you can find your image data by using asset local identifier instead of PHImageFileURLKey.

My code for your reference:

You can use your asset's local identifier and will get the image in response.

PHFetchResult *savedAssets = [PHAsset fetchAssetsWithLocalIdentifiers:@[asset.localIdentifier] options:nil];
    [savedAssets enumerateObjectsUsingBlock:^(PHAsset *asset, NSUInteger idx, BOOL *stop) {

        //this gets called for every asset from its localIdentifier you saved
        PHImageRequestOptions * imageRequestOptions = [[PHImageRequestOptions alloc] init];
        imageRequestOptions.synchronous = YES;
        imageRequestOptions.deliveryMode = PHImageRequestOptionsResizeModeFast;

        [[PHImageManager defaultManager]requestImageForAsset:asset targetSize:CGSizeMake(50,50) contentMode:PHImageContentModeAspectFill options:imageRequestOptions resultHandler:^(UIImage * _Nullable result, NSDictionary * _Nullable info) {
            NSLog(@"get image from result");

        }];
    }];

Upvotes: 1

Related Questions