How to save image into Photos
Without that crazy Objective-C method that requires selector.
Published: April 19, 2021 Sponsored App StoreI recently needed to save an image into the Photos library. However most approaches I found on the web used the crazy method from ObjC times..
UIImageWriteToSavedPhotosAlbum(image: UIImage, completionTarget: Any?, completionSelector: Selector?, contextInfo: UnsafeMutableRawPointer?)
You are supposed to create another method that will be called after this finishes. 🥴
Thankfully I found method that uses PHPhotoLibrary
and has a few benefits. So this post is there mainly for myself for next time I need to save something to Apple Photos library.
Preparation
To use the PHPhotoLibrary
you need to import Photos
and modify your Info.plist
.
In your Info.plist
add the key NSPhotoLibraryAddUsageDescription
. This assumes you are only going to save stuff, not read or modify the existing.
Saving UIImage to Photos
And next if you have an UIImage
, you can save it like this:
PHPhotoLibrary.shared().performChanges {
_ = PHAssetChangeRequest.creationRequestForAsset(from: image)
} completionHandler: { (success, error) in
}
You only have to create the request and it will save the image thanks to the performChanges
block. In the real world, you would also need to implement the completion handler 🙂
Saving image from file to Photos
This approach has the benefit that you can also provide a URL for the image instead. You don't have to load the data into UIImage
and this will also keep all the available metadata, as Apple notes in the docs.
_ = PHAssetChangeRequest.creationRequestForAssetFromImage(atFileURL: imageUrl)
Saving videos
Want to save video to Photos library? No problem. Use the same approach above, just with different creation request:
_ = PHAssetChangeRequest.creationRequestForAssetFromVideo(atFileURL: videoUrl)
And that's basic saving into Photos library done.
Uses: Xcode 12 & Swift 5.3