从我的 UIView 截图并将其保存为图像或 PDF Swift 5, Xcode 13, iPad

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

在此处找到: 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!
}

我想使用此代码从我的 viewcontroller 获取图像。之后我想将图像保存到我的照片库中以便打印和通过邮件发送。

仅当我在 return 图像的倒数第二行中添加此代码时!:

 UIImageWriteToSavedPhotosAlbum(image, nil, nil, nil)

,我收到“信号 SIGABRT”错误。

在我的 info.plist 中,我尝试添加:Privacy - Photo Library Usage Description 没有任何价值。 谁能帮我找出问题所在? 另一种选择是将屏幕截图以 pdf 格式保存在任何文件夹中,以便稍后在发送和打印时找到它。 感谢您的任何提示。

使用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.