Skip to content

Instantly share code, notes, and snippets.

@andresr-dev
Last active April 27, 2022 19:55
Show Gist options
  • Select an option

  • Save andresr-dev/1e8cb3b92ef07a7b9a36aaaddc686441 to your computer and use it in GitHub Desktop.

Select an option

Save andresr-dev/1e8cb3b92ef07a7b9a36aaaddc686441 to your computer and use it in GitHub Desktop.
This is a handy class that you can use to save an image to your photos library and below there is an example of how to use it. IMPORTANT: You must provide a message in "Privacy - Photo Library Additions Usage Description" of your target info in order to be able to use this class!
import UIKit
class ImageSaver: NSObject {
var successHandler: (() -> Void)?
var errorHandler: ((Error) -> Void)?
func writeToPhotoAlbum(image: UIImage) {
UIImageWriteToSavedPhotosAlbum(image, self, #selector(saveCompleted), nil)
}
@objc func saveCompleted(_ image: UIImage, didFinishSavingWithError error: Error?, contextInfo: UnsafeRawPointer) {
if let error = error {
errorHandler?(error)
} else {
successHandler?()
}
}
}
// How to use it
import SwiftUI
struct SaveImageExample: View {
@State private var image: UIImage?
var body: some View {
VStack {
Image(uiImage: image ?? UIImage())
.resizable()
.scaledToFit()
.onAppear(perform: loadImage)
Button("Save Image", action: save)
}
}
func loadImage() {
image = UIImage(named: "Example")
}
func save() {
guard let image = image else { return }
let imageSaver = ImageSaver()
imageSaver.successHandler = {
// Show a success alert to user
}
imageSaver.errorHandler = { error in
// Show a error alert to user
}
imageSaver.writeToPhotoAlbum(image: image)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment