Apple iOS Development Photo frame detailed

Source: Internet
Author: User



I. Overview



In IOS devices, photos and videos are a significant part of the process. Just in the process of making a custom iOS image selector, sort out the way you use the photo frame in iOS. Prior to the advent of iOS 8, developers could only use the Assetslibrary framework to access the device's photo gallery, a framework that was a bit behind the pace of iOS application development and code design principles but really powerful, considering that IOS7 still had a lot of penetration, so assetslibrary Is the part of this article that focuses on this. After the advent of iOS8, Apple provided a framework called Photokit, a framework that allows applications to be better connected to the device photo gallery, and this framework is also introduced at the end of this article.



It is also worth emphasizing that in IOS, photo gallery is not just a collection of photos, but includes video. In Assetslibrary, both have the same type of object to describe, but the type is different. For convenience, most of the time you use "resources" to represent "photos and videos" in IOS.



Two. Introduction to Assetslibrary composition



The composition of the assetslibrary is in line with the composition of the photo library itself, the complete Photo gallery objects, albums, photos can be found in the Assetslibrary one by one corresponding composition, which makes the use of assetslibrary become intuitive and convenient.



Assetslibrary: Represents the resource pool (photo gallery) throughout the device and can be captured and included in the device by assetslibrary photos and videos
Alassetsgroup: Map an album in photo gallery, Alassetsgroup to get information about an album, resources under a photo album, and add resources to an album.
Alasset: Map a photo or video from a photo gallery, Alasset to get detailed information about a photo or video, or to save photos and videos.
Alassetrepresentation:alassetrepresentation is a alasset encapsulation (but not a subclass) that makes it easier to get resource information in Alasset, with at least one of each alasset Alassetrepresentation object, which can be obtained by defaultrepresentation. For example, using a system camera to take raw + JPEG photos, there will be two alassetrepresentation, one that encapsulates the raw information for the photo, and the other encapsulates the JPEG information for the photo.
Three. Basic use of Assetslibrary
Assetslibrary has a lot of functions, basically can be divided into the acquisition/save two parts, save the part of relatively simple, API is relatively small, so this does not make detailed introduction. The API for obtaining resources is richer, and a common example of using a large number of Assetslibrary APIs is the picture selector (Alasset Picker). To make a picture selector, the idea is to get a photo gallery-list All albums-show all the pictures in the album-Preview the Big picture.



The first is to check whether the APP has a photo-operation license:


Nsuinteger _targetindex; Index target value, pull resource until this value is manually stopped pull
Nsuinteger _currentindex; Current index, starting at this value each time the resource is pulled
_targetindex = 50;
_currentindex = 0;

-(void) Loadassetwithassetsgroup: (Assetsgroup *) Assetsgroup {
[Assetsgroup enumerateassetsatindexes:[nsindexset Indexsetwithindex:_currentindex] Options:NSEnumerationReverse usingblock:^ (Alasset *result, Nsuinteger index, BOOL *stop) {
_currentindex = index;
if (Index > _targetindex) {
If the index of the pull resource is larger than the target value, stop pulling *stop = YES;
} else {
if (result) {
[_imagesassetarray Addobject:result];
} else {
Result is nil, that is, traverse photo or video complete}
}
}];
}
The previously pulled data has been displayed, you need to display new data, call the Loadassetwithassetsgroup method again, and update the _targetindex value as needed



If you have obtained authorization, you can get a list of albums:


assetslibrary = [[Alassetslibrary alloc] init]; _albumsarray = [[Nsmutablearray alloc] init]; [_assetslibrary enumerategroupswithtypes:alassetsgroupall usingblock:^ (alassetsgroup *group, BOOL *stop) {     if (group) {         [group setassetsfilter:[ Alassetsfilter allphotos]];         if (group.numberofassets > 0) {             //Storing albums in an array to facilitate later display of albums using               [_albumsarray addobject:group];         }    } else {         if ([_ Albumsarray Count] > 0 {            //Save all albums, Can show albums list         } else {            //No albums with resources, output tips         }     } failureblock:^ (Nserror *error) {     NSLog (@ "Asset Group not found!\n" ); }];
In the code above, iterate through the list of albums and store references to an array of albums Alassetgroup objects that are not empty in the album. Here are a few points to emphasize:


Allow the album to be empty in IOS, that is, there is no resources in the album, if you do not want to get an empty album, you need to like the code in the above manual filtering
Alassetsgroup has a setassetsfilter way to pass in a filter that controls only the photos in the album or just the video. Once the filter is set, the resource list and the amount of resources in the Alassetsgroup are automatically updated.
The acquisition and preservation of albums and resources throughout the assetslibrary is using asynchronous processing (asynchronous), taking into account the relatively large (and possibly large) size of the resource file. For example, the above traversal photo album operation, the results of the album using block output, if the album traversal completed, then the last output block of the group parameter value is nil. The stop argument is used to stop the traversal manually, and the next traversal is stopped as long as the *stop is set to YES. This often leads to misunderstandings, so it is important to note that.
Now that you have a photo album, the next step is to get the resources in the album:



imagesassetarray = [[Nsmutablearray alloc] init]; [Assetsgroup enumerateassetswithoptions:nsenumerationreverse usingblock:^ (alasset *result, NSUInteger index, BOOL * Stop) {     if (result) {         [_imagesassetarray addobject:result];    } else {        //result is nil, That is, walk through the photo or video, you can show the resource list     }]; The
is similar to the process of traversing a photo album, which is also a series of asynchronous methods in which the above method outputs a block in which, in addition to the result parameter represents the resource information, the stop is used to manually stop the traversal and also provides an index parameter that represents the indexes of the resource. In general, the display resource list uses thumbnails (Result.thumbnail), so that even though there is a lot of resources, the speed of traversing resources can be quite rapid. However, if you do need to load a high definition map of the resource or other time-consuming processing, you can use the index argument and the stop argument above to make a segment pull resource. For example,


Nsuinteger _targetindex; Index target value, pull resources until this value is manually stopped pulling Nsuinteger _currentindex; Current index, starting at this value each time the resource is pulled _targetindex = 50; _currentindex = 0;  -(void) Loadassetwithassetsgroup: (Assetsgroup *) Assetsgroup {     [Assetsgroup enumerateassetsatindexes:[nsindexset Indexsetwithindex:_currentindex] Options:NSEnumerationReverse usingblock:^ (Alasset *result, Nsuinteger index, BOOL *stop) {         _ Currentindex = index;         if (Index > _targetindex) {             //Pull Resource Index if it is larger than the target value, stop pull               *stop = yes;        } else {             if (result) {                  [_imagesassetarray addobject:result];             } else {                 //result is nil, that is, traverse the photo or video complete              }        }    }]; } //Pull data is already displayed, need to display new data, recall Loadassetwithassetsgroup method, and update _targetindex value as needed
The final step is to get picture details, such as:


//Get the detailed resource information of the resource picture, where Imageasset is the Alasset object of a resource alassetrepresentation *representation = [Imageasset Defaultrepresen Tation]; Get the resource picture of the fullscreenimage uiimage *contentimage = [UIImage imagewithcgimage:[representation fullscreenimage]];
For a alassetrepresentation, it contains multiple versions of the picture. The most commonly used are fullresolutionimage and fullscreenimage. Fullresolutionimage is the original image of the picture, the image obtained through fullresolutionimage without any processing, including through the System album "Edit" function after the processing of the information is not included, so you need to show the "edit" function after processing information, using Fullresolutionimage is more inconvenient, the other fullresolutionimage pull will also be relatively slow, in more than one Fullresolutionimage switch can obviously feel the image loading process. Therefore, it is recommended to get a picture of the fullscreenimage, it is a full screen version of the picture, this version contains the system through the "edit" function of the information, but also a thumbnail, but the image is very little distortion, the disadvantage is that the size of the picture is a fit screen size version, As a result, there is a need for additional processing when displaying pictures, but considering the reason for the very fast loading (the switch between multiple pictures does not feel the load time of the picture), it is recommended that fullscreenimage be used.



The process of the system album is probably the same as the above, you can see that throughout the process did not use the picture of the Fullresolutionimage, from the album list to the final view of resources, are using thumbnails, which is also a fast-growing IOS album is an important reason.



Three. Assetslibrary's pit point
As an old frame, assetslibrary not only have pits, but also a lot of, in addition to the above mentioned resources asynchronous pull to pay attention to matters, the following points are noteworthy:



1. Assetslibrary instance requires strong reference
Instance after a assetslibrary, as shown above, we can get to the desired albums and resources through a series of enumeration methods and store them in an array for easy presentation. However, when we store these captured albums and resources in an array, we actually just store these albums and resources in the Assetslibrary reference (pointers), so regardless of the albums and resources stored in the array after the use of this data, the first need to ensure that Assetslibrary is not released by ARC, or when the data is removed from the array, the corresponding reference data is found to be missing (see figure below). This is easier to ignore, so it is recommended that, in the use of Assetslibrary Viewcontroller, assetslibrary be used as a strongly held property or private variable, to avoid being cited Assetslibrary Assetslibrary is released by ARC after the data needed in the



The following figure: Instantiate a assetslibrary local variable, enumerate all albums and store them in an array named _albumsarray, look at the array again when the album is displayed, and find that the data in Alassetsgroup has been lost.






2. Assetslibrary follows the principle of written precedence
Write-first is that, in the process of reading resources using Assetslibrary, there are any other processes (not necessarily the same App) that receive alassetslibrarychangednotification when saving resources. Lets the user interrupt the read operation on its own. The most common is read fullresolutionimage, with the process in writing, because the reading fullresolutionimage time-consuming, it is easy to exception.



3. Open Photo Stream easily lead to exception
In essence, this is the same problem as the above assetslibrary adherence to the write precedence principle. If the user turns on the shared photo stream (Photo stream), the shared photo stream is Mstreamd "secretly", and when someone writes the photo to Camera Roll, it is automatically saved to the Photo stream Album, if the user is just reading it, That's the same as what it says. Exception. Because the shared photo stream is the user's decision to open, the developer cannot change it, but it is possible to turn off frequent notification messages that are generated by the listener's shared photo stream at a time when protection is needed at the following interface.



1 [alassetslibrary Disablesharedphotostreamssupport];
Four. Photokit Introduction
Photokit is a more complete and efficient library than assetslibrary, and the processing of resources differs greatly from that of assetslibrary.



First, briefly introduce a few concepts:



Phasset: Represents a resource in photo gallery, similar to Alasset, which enables you to capture and save resources through Phasset
Phfetchoptions: Parameters to obtain resources, can be passed nil, even with the system defaults
Phfetchresult: Represents a collection of resources, or a collection of albums
Phassetcollection: Represents an album or a moment, or is a "smart album" (The system provides a specific series of albums, such as: recently deleted, video lists, favorites, etc., as shown in the following figure)
Phimagemanager: Used to handle the loading of resources, the process of loading pictures with cache processing, can be passed into a phimagerequestoptions control of the output size of the resources and other specifications
Phimagerequestoptions: As mentioned above, control a series of parameters when loading pictures
The second section of UITableView in the figure below is all the smart albums listed in Photokit






A few more snippets show how to get the code for the photo album and the resources under an album:



List all album Smart albums Phfetchresult *smartalbums = [phassetcollection fetchassetcollectionswithtype: Phassetcollectiontypesmartalbum Subtype:phassetcollectionsubtypealbumregular Options:nil];
Lists all user-created albums Phfetchresult *toplevelusercollections = [Phcollectionlist fetchtoplevelusercollectionswithoptions: NIL];
Gets a collection of all resources, sorted by the creation time of the resource phfetchoptions *options = [[Phfetchoptions alloc] init];
Options.sortdescriptors = @[[nssortdescriptor sortdescriptorwithkey:@ "CreationDate" Ascending:YES]];
Phfetchresult *assetsfetchresults = [Phasset fetchassetswithoptions:options];
Gets the first collection in the collection of resources and gets the picture phcachingimagemanager *imagemanager = [[Phcachingimagemanager alloc] init];
Phasset *asset = assetsfetchresults[0];
[Imagemanager Requestimageforasset:asset
Targetsize:somesize
Contentmode:phimagecontentmodeaspectfill
Options:nil
resulthandler:^ (UIImage *result, nsdictionary *info) {

Get a piece of uiimage and show it to the interface.
}];
Combined with the above code fragment, Photokit relative assetslibrary has three major improvements:


Get data from assetslibrary, whether it's a photo album, or a resource, essentially using enumerations to traverse the photo gallery to get the appropriate data. And the Photokit is to obtain the corresponding data directly by passing in the parameter, thus the efficiency will improve quite a lot.
in Assetslibrary, albums and resources correspond to different objects (Alassetgroup and Alasset), so capturing albums and obtaining resources is two completely unrelated interfaces. And Photokit has phfetchresult this can be a unified storage of albums or resources objects, so processing albums and resources will also be more convenient.
Photokit Returns the metadata of the resource when the resource result is returned, obtaining the metadata is a difficult thing to do in Assetslibrary. At the same time through Phasset, developers can also directly obtain whether the resources are collected (favorite) and hidden (hidden), whether to open the image of HDR or panorama mode, or even through a continuous picture to capture the other pictures in the shot. This is also the beginning of the article, Photokit can be better with the device photo library access to an important factor.


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.