swiftuiimageios-cameraphotokitcamera-roll

How to temporarily save UIImage to Camera Roll


I know that I can save an UIImage to Camera Roll/Photo Album using the following code.

let image = UIImage(data: data) {
    UIImageWriteToSavedPhotosAlbum(image, nil, nil, nil)
}

However, this does not provide for a way to know where that image is specifically stored as there is no direct path.

I was wondering if it is possible to save an image to camera roll, and then, later on, is it possible to delete that exact image using swift code alone.


Solution

  • This is totally possible! However, you would need to use the PhotoKit framework for that. You can find the complete documentation for it here.

    There is a nice sample project, that also shows how to delete photos (<- links directly to the deletion section) referenced from that documentation page.

    To save the image in the first place, you would need to use the PHAssetChangeRequest instead of UIImageWriteToSavedPhotosAlbum. Specifically, there's PHAssetChangeRequest.creationRequestForAsset(from:).

    Keep in mind that you need to execute change requests (both for creation and deletion) from within a performChanges call on the PHPhotoLibrary.

    Btw. if you retrieve the image from somewhere and need to preserve the metadata (like Exif data), you should use PHAssetChangeRequest.creationRequestForAssetFromImage(atFileURL:) to create the asset.

    Hope this helps to get you started.