How too save image to Photo library in iOS

Issue #790

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
        )
    }
}
Written by

I’m open source contributor, writer, speaker and product maker.

Start the conversation