Access media/photos/videos using ALAssetsLibrary iOS/Objective-C

Introduction
With the progressive success to media applications in growing social market, the access to Media Library over iOS device is more or less one of the core requirement. This post focuses on using the ALAssetsLibrary to get access to your media on your iOS device.

What is ALAssetsLibrary ?
ALAssetsLibrary is core class added to the framework to get access to the media on your iOS device. This library was introduced in iOS 5 and has an extensive use in the media applications. All the methods, constants and other connecting libraries are listed over Apple Developer documentation.

Code Time!!!
To use the ALAssetsLibrary in your code, you will be required to import the header file into your class.

 #import <AssetsLibrary/AssetsLibrary.h>

Once the header file is added to your code, you will have access to the methods and constants that are predefined in the header file. With the code assistance provided by Xcode, you can check out other methods available that can be useful in different situations.

Now create a ALAssetsLibrary Object into your scope to be used for accessing media of your device.

ALAssetsLibrary *assetLibrary = [[ALAssetsLibrary alloc] init];

First of all to access the library you will be required check whether the user has authorized your app to access the media or not.

if([ALAssetsLibrary authorizationStatus])
{
//Library Access code goes here
}
else{
UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"Permission Denied" message:@"Please allow the application to access your photo and videos in settings panel of your device" delegate:[PHCPCSyncController getSharedSyncInstance] cancelButtonTitle:@"Ok" otherButtonTitles: nil];
[alertView show];
}

 

The above constant authorizationStatus checks whether the user of application has provided access to the application to access the Assets or not. In case not then it shows up a alert to the end user to enable manually via Settings. One thing to remember there is no way you can change the settings through your app programatically. So this has to be done manually as its upto end user to allow access to Assets for the particular application.

Now if authorizationStatus returns true then you will be able to access the Assets. Lets move ahead and see how to do this stuff.

[assetLibrary enumerateGroupsWithTypes:ALAssetsGroupAll usingBlock:^(ALAssetsGroup *group, BOOL *stop) {
if(group)
{
//Filter photos
photoArray = [self getContentFrom:group withAssetFilter:[ALAssetsFilter allPhotos]];
//Enumerate through the group to get access to the photos.

[contentDictionary setObject:photoArray forKey:@"Photos"];

//Filter videos

videoArray = [self getContentFrom:group withAssetFilter:[ALAssetsFilter allVideos]];
[contentDictionary setObject:videoArray forKey:@"Videos"];

[[NSNotificationCenter defaultCenter] postNotificationName:@"assetread" object:nil];

}
} failureBlock:^(NSError *error) {
NSLog(@"Error Description %@",[error description]);
}];

 

There are groups in AssetsLibrary one is for Photos and other for Videos. The above method enumerateGroupsWithTypes:usingBlock helps to do fast enumeration over the groups that exists in the library.

Now to get access to a specific group, we setup a filter using setFilter:
We can provide the specific filter in the initialization also but here we specified ALAssetsGroupAll to access all the media provided.

Once we have attached the specified filter to group we can access the media in that group. I did that in a separate method to keep the understanding clean.

-(NSMutableArray *) getContentFrom:(ALAssetsGroup *) group withAssetFilter:(ALAssetsFilter *)filter
{
NSMutableArray *contentArray = [NSMutableArray array];
[group setAssetsFilter:filter];

[group enumerateAssetsUsingBlock:^(ALAsset *result, NSUInteger index, BOOL *stop) {

//ALAssetRepresentation holds all the information about the asset being accessed.
if(result)
{

ALAssetRepresentation *representation = [result defaultRepresentation];

//Stores releavant information required from the library
NSMutableDictionary *tempDictionary = [[NSMutableDictionary alloc] init];
//Get the url and timestamp of the images in the ASSET LIBRARY.
NSString *imageUrl = [representation UTI];
NSDictionary *metaDataDictonary = [representation metadata];
NSString *dateString = [result valueForProperty:ALAssetPropertyDate];

// NSLog(@"imageUrl %@",imageUrl);
// NSLog(@"metadictionary: %@",metaDataDictonary);

//Check for the date that is applied to the image
// In case its earlier than the last sync date then skip it. ##TODO##

NSString *imageKey = @"ImageUrl";
NSString *metaKey = @"MetaData";
NSString *dateKey = @"CreatedDate";

[tempDictionary setObject:imageUrl forKey:imageKey];
[tempDictionary setObject:metaDataDictonary forKey:metaKey];
[tempDictionary setObject:dateString forKey:dateKey];

//Add the values to photos array.
[contentArray addObject:tempDictionary];
}
}];
return contentArray;
}

 

This method takes the group and filter as an input, process over media and returns the array consisting of custom data.
ALRepresentation is class used to represent a particular asset. Once we have the representation from the asset, we are allowed to access various attributes of the object. All these can be found in ALAsset Class available in the Apple Developer Documentation. To know more about the options please refer to the documentation.

I hope so you enjoyed the post, look forward to more in near future!!!
Thanks for your time 🙂

2 thoughts on “Access media/photos/videos using ALAssetsLibrary iOS/Objective-C”

  1. I wish you had added in the sections for requesting permission and for displaying the actual views needed to select images. I’m over here pulling out my hair because this just confused me even more.

    Like

    1. Hey Ryan, Thanks for checking the post. There are significant amount of changes since i wrote this one. Moreover this is just for the reference to give you the idea, actual requirements differ from situation to situation. But still i will consider your suggestion and will try to see what i can provide here.

      Like

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s