IOS development ------ simple multi-Choice of images (AssetsLibrary)

Source: Internet
Author: User

IOS development ------ simple multi-Choice of images (AssetsLibrary)

AssetsLibrary. the framework is a static library used before iOS7.0 to obtain all media resources of the mobile phone. Photo can be used after iOS8.0. framework, but because iOS7 adaptation is involved, this library is still used a lot.

In fact, multiple-choice images have many useful third parties, but it is not that easy to find a third party that fully meets your needs. Even if you do not understand it, it is not easy to modify the code, so it is also necessary to understand this database. Here we will record the understandings and problems in the process.

If your friends have any interesting libraries, please introduce them. I hope you can share them with those who like to study technology.
The following content is used while reading the development documentation, and written according to your own understanding. If an error occurs, please let me know.Thanks()

All code in this article: https://github.com/YRunIntoLove/YAImagePickerView

 

Class Logic

To study a database or framework, the overall logic must be clear. The following is my understanding:
-ALAssetsLibrary is a resource library. All resource groups are initially obtained from objects of this class.
-ALAssetsGroup is a resource group that contains basic information about each Resource Group and all resources. You can set the filter attribute to select the desired resource type.
-ALAssetsFilter is a filter. For example, you need to traverse all resources from the Resource Group, video resources or image resources.
-ALAsset is a resource object that can obtain group information. For details, you can obtain the detailed object of the resource.
-ALAssetRepresentation is the detailed information of the resource object. The detailed content of ALAsset exists in this class. For example, a high-definition graph exists in this object.

 

Classes in the class library and Their attribute Methods

All the attributes and methods used in the Code are mentioned here. If you only select multiple graphs, the following methods should be sufficient. If not, you canCommand + ClickGo to the development documentation.
 

ALAssetsLibrary

Resource library object:

/***** Related types **/ALAssetsGroupLibrary // album content from iTunes (for example, self-contained sunflower photos) ALAssetsGroupAlbum // photos generated by the device itself or synchronized from iTunes, but do not include photos in the photo stream or sharing stream. (For example, images saved from various software) ALAssetsGroupEvent // album generated by the camera interface event ALAssetsGroupFaces // facial album (Unclear) ALAssetsGroupSavedPhotos // The photo ALAssetsGroupPhotoStream in the album film // The photo stream ALAssetsGroupAll // except the content above ALAssetsGroupLibrary
/* Traverse related resource groups */-(void) Configure :( ALAssetsGroupType) types usingBlock :( optional) enumerationBlock failureBlock :( ALAssetsLibraryAccessFailureBlock) failureBlock;

 

ALAssetsGroup

Resource Group object:

/*** Attribute key ***/extern NSString * const ALAssetsGroupPropertyName; // The group title extern NSString * const ALAssetsGroupPropertyType; // The group type extern NSString * const struct; // The IDextern NSString * const ALAssetsGroupPropertyURL of the group; // the url of the group stored locally
// Method for obtaining the relevant property. The property value can be obtained from the preceding property key-(id) valueForProperty :( NSString *) property; // obtain the resource group preview-(CGImageRef) posterImage; // set the filter-(void) setAssetsFilter :( ALAssetsFilter *) filter; // number of resources in the current group, if a filter object is set, this number is the number of storage resource objects after filtering-(NSInteger) numberOfAssets;
/*** Method of traversing resources *** // traverse all resources-(void) enumerateAssetsUsingBlock :( ALAssetsGroupEnumerationResultsBlock) enumerationBlock; // traverse resources by type-(void) enumerateassetswitexceptions :( NSEnumerationOptions) option usingBlock :( ALAssetsGroupEnumerationResultsBlock) enumerationBlock;
// Type typedef NS_OPTIONS (NSUInteger, NSEnumerationOptions) {NSEnumerationConcurrent = (1UL <0), // Order (Default) NSEnumerationReverse = (1UL <1), // reverse };

 

ALAssetsFilter

Resource filter:

// Obtain all the photo Resources in the group + (ALAssetsFilter *) allPhotos; // obtain all the video resources in the group + (ALAssetsFilter *) allVideos; // obtain all resources in the group + (ALAssetsFilter *) allAssets;

 

ALAsset

Resource object:

/*** Key of the relevant attribute ***/extern NSString * const ALAssetPropertyType; // The type of the resource object extern NSString * const ALAssetPropertyLocation; // resource object location description extern NSString * const ALAssetPropertyDuration; // resource object duration (for video-type resource objects) extern NSString * const ALAssetPropertyOrientation; // resource object direction, such as: left turn, right turn .. extern NSString * const ALAssetPropertyDate; // creation time object of the resource object extern NSString * const ALAssetPropertyRepresentations; // array of available detailed objects of the resource object extern NSString * const ALAssetPropertyURLs; // URLsextern NSString * const ALAssetPropertyAssetURL of the detailed object of the resource object; // resource ID code of the resource object/*** key of the related type ***/extern NSString * const ALAssetTypePhoto; // image type extern NSString * const ALAssetTypeVideo; // video type extern NSString * const ALAssetTypeUnknown; // location type
// Method for obtaining relevant attributes. The property value can be obtained from the preceding attribute key, which is the same as ALAssertGroup-(id) valueForProperty :( NSString *) property // a convenient method for getting detailed information about an object-(ALAssetRepresentation *) defaultRepresentation; // get a square thumbnail, but it is not recommended. It is too vague-(CGImageRef) thumbnail; // obtain a scaled thumbnail. It is recommended that you use this thumbnail. (This attribute is used in the Demo)-(CGImageRef) aspectRatioThumbnail;

 

ALAssetRepresentation

Resource details object:

// Orientation of the current object-(ALAssetOrientation) orientation; // get the scale-(float) scale;
// Obtain a full-screen HD image (this attribute is obtained for the previewed HD image in the Demo)-(CGImageRef) fullScreenImage; // if this attribute is used, directly use this method to generate the UIImage object UIImage * image = [UIImage imageWithCGImage: fullScreenImage];
// Obtain a processed full-screen HD image (CGImageRef) fullResolutionImage; // if you use this attribute, You need to generate a UIImage object using the following method, otherwise, an error such as the display direction will occur, and the image will become a UIImage with a left turn of 90 degrees * image = [UIImage imageWithCGImage: fullResolutionImage scale: fullResolutionImage. scale orientation: fullResolutionImage. orientation];

 

Demo code configuration file _ YEnumConfig
/// YEnumConfig. h // YChoosePicturesDemo /// Created by YueWen on 16/4/15. // Copyright? 2016 YueWen. all rights reserved. // # ifndef YEnumConfig_h # define YEnumConfig_h @ import UIKit; @ import AssetsLibrary; # pragma mark-typedef enum: NSUInteger {YChoosePhotoSequenceTypeDefault = 0, // by default, YChoosePhotoSequenceTypeDate // in the photo album order} YChoosePhotoSequenceType; # pragma mark-// callback typedef void (^ ImagesBlock) (NSArray
  
   
*); # Pragma mark-YPhotoManagertypedef void (^ ALAssetGroupBlock) (NSArray * groups); typedef void (^ ALAssetPhotoBlock) (NSArray * photos); typedef void (^ ALAssetFailBlock) (NSString * error); # pragma mark-YPhotoCollectionViewCelltypedef void (^ YPhotoCollectionViewBlock) (void); # endif/* YEnumConfig_h */
  

 

Image request_yphotomanager

According to the habits, we still createdYPhotoManagerSingleton

@ Interface YPhotoManager () @ property (nonatomic, strong) ALAssetsLibrary * library; // resource library @ property (nonatomic, copy) ALAssetGroupBlock; // Resource Group callback @ property (nonatomic, strong) NSMutableArray * groups; // array object for storing all photo groups @ property (nonatomic, strong) NSMutableArray * photos; // array object for storing all photos @ end
Create a separate album
/*** Create a photo group named title ** @ param title group name */-(void) createGroupWithTitle :( NSString *) title {// start to create [self. library addAssetsGroupAlbumWithName: title resultBlock: ^ (ALAssetsGroup * group) {// coding success} failureBlock: ^ (NSError * error) {// coding error}];}
Request all photo groups

Reading all resource group objects is actually enumeration traversal. Every time a group object is obtained, a callback will be performed, and the synchronization will be slightly choppy, so asynchronous callback Block is used.

# Pragma mark-all groups that read the album/*** all groups that read the album ** @ param groupBlock callback for successful Group acquisition * @ param failBlock failure callback * @ param cameraRollHandle camera callback when the film size is not nil */-(void) readAllPhotoGroups :( ALAssetGroupBlock) groupBlock Fail :( ALAssetFailBlock) failBlock CameraRollHandel :( void (^) (void) cameraRollHandle {// delete all groups previously stored [self. groups removeAllObjects]; _ block _ weak typeof (self) copy_self = self; // start traversing [self. library enumerateGroupsWithTypes: ALAssetsGroupAll usingBlock: ^ (ALAssetsGroup * group, BOOL * stop) {// if the returned group contains if (group) {// filter the group, as long as the photo [group setAssetsFilter: [ALAssetsFilter allPhotos]; // Add data [copy_self.groups addObject: group]; // perform sequential judgment, the purpose is to put the film album first. if ([self containCameraRoll: group] = true) {// Delete the array [self. groups removeObjectAtIndex: self. groups. count-1]; [self. groups insertObject: group atIndex: 0];} // callback data groupBlock ([NSArray arrayWithArray: copy_self.groups]); // callback if ([self containCameraRoll: group] = true) cameraRollHandle () ;}} failureBlock: ^ (NSError * error) {// failure callback failBlock (error. localizedDescription);}];}

All the groups are loaded here, so the camera film group won't be the first, but you want it to be in the first line. Add this judgment to ensure that there is a camera film, prepare for other operations:

/*** Determine whether the camera film is included ** @ param group ALAssetsGroup object ** @ return true indicates inclusion, false indicates inclusion, and vice versa */-(BOOL) containCameraRoll :( ALAssetsGroup *) group {// if it is a camera film, put it first. Here it is only applicable to English and Chinese NSString * nameCN = NSLocalizedString ([group valueForProperty: ALAssetsGroupPropertyName], @ ""); NSString * nameEN = NSLocalizedString ([group valueForProperty: ALAssetsGroupPropertyName], @ ""); // sort the current number of groups if ([nameCN isw.tostring: @ "Camera film"] | [nameEN Isen tostring: @ "Camera Roll"]) {// modify the variable return true;} return false ;}
All photo Resources in the request Group

1. To request resources in a group, open the Group Object first.

# Pragma mark-open photo Group-(void) openPhotosGroup :( ALAssetsGroup *) assetsGroup Success :( ALAssetPhotoBlock) successBlock Fail :( ALAssetFailBlock) failBlock {// delete all photo objects [self. photos removeAllObjects]; // avoid strongly referencing _ block _ weak typeof (self) copy_self = self; // obtain the url data of the current group NSURL * url = [assetsGroup valueForProperty: ALAssetsGroupPropertyURL]; // open the current resource group object [self. library groupForURL: url resultBlock: ^ (ALAssetsGroup * group) {[copy_self photosInGroups: group Block: successBlock];} failureBlock: ^ (NSError * error) {// failed callback failBlock (error. localizedDescription);}];}

2. traverse the opened group and call back the data.

// Obtain all the photo objects and call back the data-(void) photosInGroups :( ALAssetsGroup *) group Block :( ALAssetPhotoBlock) photoBlock {// start to read [group enumerateAssetsUsingBlock: ^ (ALAsset * result, NSUInteger index, BOOL * stop) {// if it is not empty or the media is an image if (result! = Nil & [[result valueForProperty: ALAssetPropertyType] isdesktostring: ALAssetTypePhoto]) {// Add data [self. photos addObject: result]; // if (index = group. numberOfAssets-1) {// callback photoBlock ([NSArray arrayWithArray: self. photos]) ;}}] ;}

The data used is basically appreciated. As for View and ViewController, it is too long to take place here. If you have any idea, you can download the code to study it.

In the end, you should not forget to set the contentMode attribute when displaying thumbnails, whether it is UIImageView or UIButton. In this way, the effects in the displayed image will be displayed:

// If the image is too large, it is displayed based on the maximum value in the height and width. Therefore, some do not display UIViewContentModeScaleAspectFill. // the opposite of the preceding attribute is displayed, it displays UIViewContentModeScaleAspectFit based on the minimum value of the end of the high width.
// If the image is displayed in CollectionCell, Set Self. contentMode = UIViewContentModeScaleAspectFill; // if the image is browsed, Set Self. contentMode = UIViewContentModeScaleAspectFit as follows;

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.