Creating New Asset Collection and PHObjectPlaceholder

Using the new PhotoKit or Photos Framework in the upcoming iOS 8, I’ve been attempting to create a photo library app. This post talks about how to add an image to a non-existent album using PhotoKit (aka Photos FrameWork).

Add to New Album

What I want to achieve is to let the user can add an image to a non-existent album. After capturing the name of the album, create a new change request to create the album.

The tricky bit is NOT to PHObjectPlaceholder directly within the same change block. If you attempt to execute addAsset: within the same change block, you’ll receive a null object.

Create a New Album

PHObjectPlaceholder *__block assetCollectionPlaceholder;
[[PHPhotoLibrary sharedPhotoLibrary] performChanges:^{
// Request creating an album from the textfield
PHAssetCollectionChangeRequest *createAlbumRequest = [PHAssetCollectionChangeRequest creationRequestForAssetCollectionWithTitle:title];
// Store placeholder object for use later
assetCollectionPlaceholder = createAlbumRequest.placeholderForCreatedAssetCollection;
} completionHandler:^(BOOL success, NSError *error){

Retrieve PHObjectPlaceholder

The next step is to retrieve a PHAssetCollection object from the PHObjectPlaceholder. How? Using fetchAssetCollectionsWithLocalIdentifiers and using the local identifier of the placeholder object to get yourself a PHFetchResult object. Since there is only 1 object, you can safely call firstObject on the fetch result to get yourself the PHAssetCollection object needed.

} completionHandler:^(BOOL success, NSError *error){
PHFetchResult *collectionFetchResult = [PHAssetCollection fetchAssetCollectionsWithLocalIdentifiers:@[assetCollectionPlaceholder.localIdentifier] options:nil];
NSLog(@"Fetch result size %d\n%@", collectionFetchResult.count, [collectionFetchResult firstObject]);
[self addAssetToAssetCollection:[collectionFetchResult firstObject]];

Adding Image to Existing Asset Collection

Now that the new album has been created, we can proceed to add the image into the asset collection. This part is straightforward, simply call changeRequestForAssetCollection with the collection that we gotten inside a change block.

[[PHPhotoLibrary sharedPhotoLibrary] performChanges:^{
PHAssetCollectionChangeRequest *changeRequest = [PHAssetCollectionChangeRequest changeRequestForAssetCollection:collection];
[changeRequest addAssets:[NSArray arrayWithObject:self.asset]];
NSLog(@"Adding asset to %@...", changeRequest.title);
} completionHandler:^(BOOL success, NSError *error){

If you have other ways of adding an image into a non-existent album, do share it by dropping a comment below.

1 reply on “ Creating New Asset Collection and PHObjectPlaceholder ”
Leave a Reply

Your email address will not be published. Required fields are marked *