blog
blog copied to clipboard
How too save image to Photo library in iOS
Use UIImageWriteToSavedPhotosAlbum
Adds the specified image to the user’s Camera Roll album.
Let's make an NSObject
delegate class so we can perform target action to notify about completion
import UIKit
struct ImageService {
final class Delegate: NSObject {
let completion: (Error?) -> Void
init(completion: @escaping (Error?) -> Void) {
self.completion = completion
}
@objc func savedImage(
_ im: UIImage,
error: Error?,
context: UnsafeMutableRawPointer?
) {
DispatchQueue.main.async {
self.completion(error)
}
}
}
func addToPhotos(image: UIImage, completion: @escaping (Error?) -> Void) {
let delegate = Delegate(completion: completion)
UIImageWriteToSavedPhotosAlbum(
image,
delegate,
#selector(Delegate.savedImage(_:error:context:)),
nil
)
}
}