- [d->library enumerateGroupsWithTypes: ALAssetsGroupAll
- usingBlock: ^(ALAssetsGroup *group, BOOL *stop) {
- NSString *name = [group valueForProperty:ALAssetsGroupPropertyName];
- if ([name length]) {
- [group enumerateAssetsUsingBlock: ^(ALAsset *asset, NSUInteger index,
- BOOL *stop) {
- if ([[asset valueForProperty: ALAssetPropertyType]
- isEqual: ALAssetTypePhoto]) {
- [d->assets addObject:asset];
- }
- }];
- }
+ PHAuthorizationStatus status = [PHPhotoLibrary authorizationStatus];
+ if (status == PHAuthorizationStatusNotDetermined) {
+ [PHPhotoLibrary requestAuthorization:^(PHAuthorizationStatus status) {
+ ios_load_random_image (callback, closure, width, height);
+ }];
+ return;
+ }
+
+ // The rest of this is synchronous.
+
+ PHFetchOptions *opt = [PHFetchOptions new];
+ opt.includeAssetSourceTypes = (PHAssetSourceTypeUserLibrary |
+ PHAssetSourceTypeCloudShared |
+ PHAssetSourceTypeiTunesSynced);
+ PHFetchResult *r = [PHAsset
+ fetchAssetsWithMediaType: PHAssetMediaTypeImage
+ options: opt];
+ NSUInteger n = [r count];
+ PHAsset *asset = n ? [r objectAtIndex: random() % n] : NULL;
+
+ __block UIImage *img = 0;
+ __block const char *fn = 0;
+
+ if (asset) {
+ PHImageRequestOptions *opt = [[PHImageRequestOptions alloc] init];
+ opt.synchronous = YES;
+
+ // Get the image bits.
+ //
+ int size = width > height ? width : height;
+ [[PHImageManager defaultManager]
+ requestImageForAsset: asset
+ targetSize: CGSizeMake (size, size)
+ contentMode: PHImageContentModeDefault
+ options: opt
+ resultHandler:^void (UIImage *image, NSDictionary *info) {
+ img = image;
+ }];
+
+ // Get the image name.
+ //
+ [[PHImageManager defaultManager]
+ requestImageDataForAsset: asset
+ options: opt
+ resultHandler:^(NSData *imageData, NSString *dataUTI,
+ UIImageOrientation orientation,
+ NSDictionary *info) {
+ // Looks like UIImage is pre-rotated to compensate for 'orientation'.
+ NSString *path = [info objectForKey:@"PHImageFileURLKey"];
+ if (path)
+ fn = [[[path lastPathComponent] stringByDeletingPathExtension]
+ cStringUsingEncoding:NSUTF8StringEncoding];
+ }];
+ }