Search code examples
iosswiftipadscreenshotphoto-gallery

Screenshot from my UIView and save it as Image or PDF Swift 5, Xcode 13, iPad


Found here: How do I take a full screen Screenshot in Swift?

func getScreenshot() -> UIImage {
    var window: UIWindow? = UIApplication.shared.keyWindow
    window = UIApplication.shared.windows[0] as? UIWindow
    UIGraphicsBeginImageContextWithOptions(window!.frame.size, window!.isOpaque, 0.0)
    window!.layer.render(in: UIGraphicsGetCurrentContext()!)
    let image = UIGraphicsGetImageFromCurrentImageContext()
    UIGraphicsEndImageContext()
    return image!
}

I want to use this code to get an image from my viewcontroller. Thereafter I wanna save the image to my photo library for printing and sending by mail.

Only when I add this code in the penultimate line over return image!:

 UIImageWriteToSavedPhotosAlbum(image, nil, nil, nil)

,I get the "signal SIGABRT" error.

In my info.plist I tried to add: Privacy - Photo Library Usage Description without any value. Can anybody help me to find what's going wrong? Another option would be to save the screenshot as pdf in any folder, to find it later for sending and printing. Thank you for any hint.


Solution

  • Use NSPhotoLibraryAddUsageDescription (Privacy - Photo Library Additions Usage Description)

    NSPhotoLibraryAddUsageDescription

    A message that tells the user why the app is requesting write-only access to the user’s photo library.

    Important

    This key is required if your app uses APIs that have write access to the user’s photo library.