In iOS, if we only need to read an image or a video or take a photo or video at a time, we can use UIImagePickerController. However, many times we need to read multiple photos or videos from PhotoLibrary at a time. At this time, we need to find another way. Fortunately, apple provides us with corresponding interfaces.
Before starting coding, we want to know several classes:
ALAssetsLibrary: indicates the entire PhotoLibrary. We can generate an Instance Object of the Image Library, which is equivalent to the handle of the Photo Library.
ALAssetsGroup: the group of the Photo Library. We can use the ALAssetsLibrary instance to obtain the handles of all the groups.
ALAsset: An ALAsset instance represents an asset, that is, a photo or video. We can obtain the corresponding subnail or source image through its instance.
One thing you need to know is blocks. apple has seen a large number of such things since iOS 4.0, which is more and more widely used, but it is really useful. I will not talk much about this stuff here. I will elaborate on my blog.
For the requirements in this article, we read the group and each asset asynchronously, but now we can use blocks in a function. So blocks is really convenient.
See the code below:
- ALAssetsLibrary * assetsLibrary = [[ALAssetsLibrary alloc] init]; // generates an instance of the entire photolibrary handle
- NSMutableArray * mediaArray = [[NSMutableArray alloc] init]; // stores the media Array
- [AssetsLibrary enumerateGroupsWithTypes: ALAssetsGroupAll usingBlock: ^ (ALAssetsGroup * group, BOOL * stop) {// obtain all Groups
- [Group enumerateAssetsUsingBlock: ^ (ALAsset * result, NSUInteger index, BOOL * stop) {// from the group
- NSString * assetType = [result valueForProperty: ALAssetPropertyType];
- If ([assetType isinclutostring: ALAssetTypePhoto]) {
- NSLog (@ "Photo ");
- } Else if ([assetType isinclutostring: ALAssetTypeVideo]) {
- NSLog (@ "Video ");
- } Else if ([assetType isinclutostring: ALAssetTypeUnknown]) {
- NSLog (@ "Unknow AssetType ");
- }
-
- NSDictionary * assetUrls = [result valueForProperty: ALAssetPropertyURLs];
- NSUInteger assetCounter = 0;
- For (NSString * assetURLKey in assetUrls ){
- NSLog (@ "Asset URL % lu = % @", (unsigned long) assetCounter, [assetUrls objectForKey: assetURLKey]);
- }
-
- NSLog (@ "Representation Size = % lld", [[result defaultRepresentation] size]);
- }];
- } FailureBlock: ^ (NSError * error ){
- NSLog (@ "Enumerate the asset groups failed .");
- }];
The rest is how to obtain the corresponding subnail or source image or other information from each asset. It's very easy.