iOS App calls the image in the album and the method to get the most recent image

  • 2020-05-19 05:59:11
  • OfStack

UIImagePickerController gets pictures from photos, galleries and albums

There are three ways to get images from iOS:

1. Directly call the camera to take photos

2. Select from a photo album

3. Select from the gallery

UIImagePickerController is the interface provided by the system to get pictures and videos.

Using the UIImagePickerController class to get pictures and videos can be divided into the following steps:

1. Initialize UIImagePickerController class;

2. Set the data source type of UIImagePickerController instance (explained below);

3. Set the setting agent;

4. Set allowsEditing =yes if image modification is required.

There are three types of data source type 1:


enum {
   UIImagePickerControllerSourceTypePhotoLibrary ,// From the gallery
   UIImagePickerControllerSourceTypeCamera ,// From the camera
   UIImagePickerControllerSourceTypeSavedPhotosAlbum // From the album
};

When using these sources it is best to check whether the following devices are supported;

 if([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera])
    {
        NSLog(@" Support the camera ");
    }
    if([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypePhotoLibrary])
    {
        NSLog(@" Support the gallery ");
    }
    if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeSavedPhotosAlbum])
    {
        NSLog(@" Support photo library ");
    }

Call the camera to get the resource

- (void)viewDidLoad {
    [super viewDidLoad];
    picker = [[UIImagePickerController alloc]init];
    picker.view.backgroundColor = [UIColor orangeColor];
    UIImagePickerControllerSourceType sourcheType = UIImagePickerControllerSourceTypeCamera;
    picker.sourceType = sourcheType;
    picker.delegate = self;
    picker.allowsEditing = YES;
}

The above is just an example of UIImagePickerController and its properties that need to be called by a pop-up window when you need to get a picture

[self presentViewController:picker animated:YES completion:nil];

We also need an agent to get the image we selected

UIImagePickerControllerDelegate
One of the three methods in agent 1, 3.0, has been deprecated, leaving only two that we need to use


- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary
 *)info;

When the user selection is complete;

- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker;

Called when the user unselects;

- (void)imagePickerController:(UIImagePickerController *)picker
 didFinishPickingMediaWithInfo:(NSDictionary *)info;

The selected information is in info, and info is a dictionary.

Keys in the dictionary:

NSString * const UIImagePickerControllerMediaType; Specify the media type selected by the user (extended at the end of the article) NSString * const UIImagePickerControllerOriginalImage; The original image NSString * const UIImagePickerControllerEditedImage; Modified image NSString * const UIImagePickerControllerCropRect; Cut size NSString * const UIImagePickerControllerMediaURL; The media URL NSString * const UIImagePickerControllerReferenceURL; The original URL NSString * const UIImagePickerControllerMediaMetadata; This value is only valid when the data source is the camera


Get the most recent image

Recent requests required me to emulate the WeChat chat prompt for the latest 1 image feature.
Let's start with the idea.
The idea is very simple, click "+" to get the list of albums, to get the latest saved 1 picture. According to the image saving time, calculate with the current timestamp to obtain the interval time. To determine whether the time interval is required. (time interval customization)
Calculation formula: current time - image saving time < = time interval
So I'm going to start writing a category based on this idea.
It is about the get function of ALAssetsLibrary, so write a classification according to it.
However, after iOS9, the library became obsolete. However, we still need to encapsulate a copy of it and then create a new tool class for adaptation.


//ALAssetsLibrary+WJ.h
#import <AssetsLibrary/AssetsLibrary.h>
@interface ALAssetsLibrary (WJ)
/**
 *  Get the latest 1 image
 *
 *  @param block The callback
 */
- (void)latestAsset:(void(^_Nullable)(ALAsset * _Nullable asset,NSError *_Nullable error)) block;
@end
//ALAssetsLibrary+WJ.m
#import "ALAssetsLibrary+WJ.h"
@implementation ALAssetsLibrary (WJ)
- (void)latestAsset:(void (^)(ALAsset * _Nullable, NSError *_Nullable))block {
    [self enumerateGroupsWithTypes:ALAssetsGroupSavedPhotos usingBlock:^(ALAssetsGroup *group, BOOL *stop) {
        if (group) {
            [group setAssetsFilter:[ALAssetsFilter allPhotos]];
            [group enumerateAssetsWithOptions:NSEnumerationReverse/* Traverse the way */ usingBlock:^(ALAsset *result, NSUInteger index, BOOL *stop) {
                if (result) {
                    if (block) {
                        block(result,nil);
                    }
                    *stop = YES;
                }
            }];
            *stop = YES;
        }
    } failureBlock:^(NSError *error) {
        if (error) {
            if (block) {
                block(nil,error);
            }
        }
    }];
}
@end

iOS8 PhotoKit already exists. Therefore, applications that write iOS8 or above can be used directly in the future.
PhotoKit simple practical packaging. See the links provided for detailed performance details.

//PHAsset+WJ.h
#import <Photos/Photos.h>
@interface PHAsset (WJ)
/**
 *  Get the latest 1 image
 */
+ (PHAsset *)latestAsset;
@end
//PHAsset+WJ.m
#import "PHAsset+WJ.h"
@implementation PHAsset (WJ)
+ (PHAsset *)latestAsset {
    // Gets a collection of all the resources and orders them by the time they were created
    PHFetchOptions *options = [[PHFetchOptions alloc] init];
    options.sortDescriptors = @[[NSSortDescriptor sortDescriptorWithKey:@"creationDate" ascending:NO]];
    PHFetchResult *assetsFetchResults = [PHAsset fetchAssetsWithOptions:options];
    return [assetsFetchResults firstObject];
}
@end

No other features are provided for this article as required (ps: most important I have just used it myself > . < ).
The image saving time can be obtained in the corresponding asset (PHAsset, AlAsset).


Related articles: