ALAssetsLibrary methods deprecated

2020-06-24 04:35发布

问题:

This is deprecated, what could be the updated code?

 ALAssetsLibrary *library = [[ALAssetsLibrary alloc] init];
    [library assetForURL:referenceURL resultBlock:^(ALAsset *asset) {
        ALAssetRepresentation *rep = [asset defaultRepresentation];

回答1:

Use below code to get all picture from Gallery: First you need to import Photo framework.

#import <Photos/Photos.h>

Take Authorization before getting image:

[PHPhotoLibrary requestAuthorization:^(PHAuthorizationStatus status)
 {
     switch (status) {
         case PHAuthorizationStatusAuthorized:
             [self performSelectorOnMainThread:@selector(getAllPictures) withObject:nil waitUntilDone:NO];
             // [self getAllPictures];
             NSLog(@"PHAuthorizationStatusAuthorized");
             break;
         case PHAuthorizationStatusRestricted:
             NSLog(@"PHAuthorizationStatusRestricted");
             break;
         case PHAuthorizationStatusDenied:
             NSLog(@"PHAuthorizationStatusDenied");
             break;
         default:
             break;
     }
 }];

-(void)getAllPicture
{
            NSLog(@"Started...");
            PHImageRequestOptions *requestOptions = [[PHImageRequestOptions alloc] init];
            requestOptions.synchronous = YES;
            PHFetchOptions *allPhotosOptions = [PHFetchOptions new];
            allPhotosOptions.sortDescriptors = @[[NSSortDescriptor sortDescriptorWithKey:@"creationDate" ascending:YES]];

            PHFetchResult *result = [PHAsset fetchAssetsWithMediaType:PHAssetMediaTypeImage options:allPhotosOptions];
            for (PHAsset *asset in result) {

                NSMutableDictionary *dic = [[NSMutableDictionary alloc] init];
                [dic setValue:asset forKey:@"assest"];
                [YOUR_ARRAY insertObject:dic atIndex:0];
                dic = nil;
            }
            NSLog(@"Completed...");
}

You can retrive image from below code:

PHImageRequestOptions *requestOptions = [[PHImageRequestOptions alloc] init];
requestOptions.synchronous = YES;

PHImageManager *manager = [PHImageManager defaultManager];
[manager requestImageForAsset:YOUR_ARRAY[INDEX_ARRAY][@"assest"]
                   targetSize:CGSizeMake(self.view.frame.size.width/3, 200)
                  contentMode:PHImageContentModeDefault
                      options:requestOptions
                resultHandler:^void(UIImage *image, NSDictionary *info) {
                    YOUR_IMAGE_VIEW.image = image;
                }];