iOS 8 Photos framework. Access photo metadata

后端 未结 6 1192
臣服心动
臣服心动 2020-12-07 11:33

I\'m looking at replacing ALAssetsLibrary with Photos framework in my app.

I can retrieve photos, collections, and asset sources just fine (even write t

6条回答
  •  萌比男神i
    2020-12-07 12:10

    I thought I'd share some code to read the metadata using the ImageIO framework in conjunction with Photos framework. You must request the image data using a PHCachingImageManager.

    @property (strong) PHCachingImageManager *imageManager;
    

    Request the image and use it's data to create a metadata dictionary

    -(void)metadataReader{
        PHFetchResult *result = [PHAsset fetchAssetsInAssetCollection:self.myAssetCollection options:nil];
        [result enumerateObjectsAtIndexes:[NSIndexSet indexSetWithIndex:myIndex] options:NSEnumerationConcurrent usingBlock:^(PHAsset *asset, NSUInteger idx, BOOL *stop) {
            [self.imageManager requestImageDataForAsset:asset options:nil resultHandler:^(NSData *imageData, NSString *dataUTI, UIImageOrientation orientation, NSDictionary *info) {
                NSDictionary *metadata = [self metadataFromImageData:imageData];
                               NSLog(@"Metadata: %@", metadata.description);
                NSDictionary *gpsDictionary = metadata[(NSString*)kCGImagePropertyGPSDictionary];
                if(gpsDictionary){
                    NSLog(@"GPS: %@", gpsDictionary.description);
                }
                NSDictionary *exifDictionary = metadata[(NSString*)kCGImagePropertyExifDictionary];
                if(exifDictionary){
                    NSLog(@"EXIF: %@", exifDictionary.description);
                }
    
                UIImage *image = [UIImage imageWithData:imageData scale:[UIScreen mainScreen].scale];
                // assign image where ever you need...
            }];
    
        }];
    }
    

    Convert NSData to metadata

    -(NSDictionary*)metadataFromImageData:(NSData*)imageData{
        CGImageSourceRef imageSource = CGImageSourceCreateWithData((__bridge CFDataRef)(imageData), NULL);
        if (imageSource) {
            NSDictionary *options = @{(NSString *)kCGImageSourceShouldCache : [NSNumber numberWithBool:NO]};
            CFDictionaryRef imageProperties = CGImageSourceCopyPropertiesAtIndex(imageSource, 0, (__bridge CFDictionaryRef)options);
            if (imageProperties) {
                NSDictionary *metadata = (__bridge NSDictionary *)imageProperties;
                CFRelease(imageProperties);
                CFRelease(imageSource);
                return metadata;
            }
            CFRelease(imageSource);
        }
    
        NSLog(@"Can't read metadata");
        return nil;
    }
    

    This has the overhead of grabbing the image, so it's not nearly as fast as enumerating your assets or collections, but it's something at least.

提交回复
热议问题