blog icon indicating copy to clipboard operation
blog copied to clipboard

How too save image to Photo library in iOS

Open onmyway133 opened this issue 3 years ago • 1 comments

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

onmyway133 avatar Mar 10 '21 05:03 onmyway133