In Swift 5.0 its possible whit:
yourView.snapshot(saveToHDR: false) { image in
UIImageWriteToSavedPhotosAlbum(image!, nil, nil, nil)
}
I use this for an AR Feature where I can take the shot whitout all Buttons on the Screen.
You can combine this whit an alert to do different things, like save or share:
Inside a Button:
yourView.snapshot(saveToHDR: false) { image in
if let saveImage = image {
self.saveAndExport(sender: sender, saveImage: saveImage)
}
}
Save and Export alert:
func saveAndExport(sender: UIButton, saveImage: UIImage){
let image: UIImage = saveImage
var exportName:String?
var alert = UIAlertController(title: "Title" , message: "Subtitle", preferredStyle: .actionSheet)
// Setup for Ipad preferredStyle: .alert cause it cant show preferredStyle: .actionSheet)
if UIDevice.current.userInterfaceIdiom == .pad {
alert = UIAlertController(title: "Title", message: "Subtitle", preferredStyle: .alert)
}
let shareFunctions = UIAlertAction(title: "Share", style: .default) { (action) in
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyyMMddhhmmss"
exportName = dateFormatter.string(from: Date()).appending(".jpg")
// }
let documentsPathUSDZ = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first!
let urlUSDZ = documentsPathUSDZ.appendingPathComponent("\(exportName!).jpeg")
do {
try image.jpegData(compressionQuality: 1.0)?.write(to: urlUSDZ, options: .atomic)
let activityController = UIActivityViewController(activityItems: [urlUSDZ], applicationActivities: nil)
activityController.popoverPresentationController?.sourceView = sender
self.present(activityController, animated: true, completion: nil)
} catch let error {
fatalError(error.localizedDescription)
}
}
let backAction = UIAlertAction(title: "Back", style: .default) { (action) in
}
let saveInPhotos = UIAlertAction(title: "Save", style: .default) { (action) in
UIImageWriteToSavedPhotosAlbum(image, nil, nil, nil)
}
let saveImage = UIImage.init(systemName: "square.and.arrow.down")
saveInPhotos.setValue(saveImage, forKey: "image")
saveInPhotos.setValue(CATextLayerAlignmentMode.left, forKey: "titleTextAlignment")
let shareImage = UIImage.init(systemName: "square.and.arrow.up")
shareFunctions.setValue(shareImage, forKey: "image")
shareFunctions.setValue(CATextLayerAlignmentMode.left, forKey: "titleTextAlignment")
let backImage = UIImage.init(systemName: "chevron.backward")
backAction.setValue(backImage, forKey: "image")
backAction.setValue(CATextLayerAlignmentMode.left, forKey: "titleTextAlignment")
alert.addAction(saveInPhotos)
alert.addAction(shareFunctions)
alert.addAction(backAction)
present(alert, animated: true, completion: nil)
}
But that doesn't work on iPad and I couldn't find a fix for. Even if I change preferredStyle to: .alert
If anyone know why help pls.