Search code examples
iosobjective-cios8photokit

Which PHAssetCollection to use for saving an image?


In iOS 8's Photos.framework, I'm trying to save a UIImage to the user's photo library, much in the same way you can long-press an image in Safari and choose the "Save Image". In iOS 7, this would be by just calling ALAssetLibrary's writeImageToSavedPhotosAlbum:metadata:completionBlock.

For iOS 8 we need to pick an asset collection to add a PHAsset to, but I can't figure out which PHAssetCollection is closest to just saving to the user's "camera roll" (even though there isn't one, really, in iOS 8)

[[PHPhotoLibrary sharedPhotoLibrary] performChanges:^{
    PHAssetChangeRequest *newAssetRequest = [PHAssetChangeRequest creationRequestForAssetFromImage:image];
    newAssetRequest.creationDate = time;
    newAssetRequest.location = location;

    PHObjectPlaceholder *placeholderAsset = newAssetRequest.placeholderForCreatedAsset;

    PHAssetCollectionChangeRequest *addAssetRequest = [PHAssetCollectionChangeRequest changeRequestForAssetCollection:WHICH_ASSET_COLLECTION];
    addAssetRequest addAssets:@[placeholderAsset];

} completionHandler:^(BOOL success, NSError *error) {
    NSLog(@"Success: %d", success);
}];

I tried accessing the "Recently Added" smart album, but it does not allow adding new content to it.


Solution

  • You don't need to mess around with PHAssetCollection. Just add by doing:

        [[PHPhotoLibrary sharedPhotoLibrary] performChanges:^{
            PHAssetChangeRequest *changeRequest = [PHAssetChangeRequest creationRequestForAssetFromImage:<#your photo here#>];
        } completionHandler:^(BOOL success, NSError *error) {
            if (success) {
                <#your completion code here#>
            }
            else {
                <#figure out what went wrong#>
            }
        }];