如何使用 UIActivityViewController 将 UIImage 分享到相机胶卷

How to share UIImage to Camera Roll using UIActivityViewController

我写这段代码是为了分享 UIImage

guard let codeImage = imgQRCode.image else {
        return
    }
    PHPhotoLibrary.requestAuthorization({status in
        if status == .authorized {
            let ac = UIActivityViewController(activityItems: [codeImage], applicationActivities: nil)
            self.present(ac, animated: true, completion: nil)
        } else {
            self.showOkAlert(messageTitle: "Access not granted", messageText: "Code image not saved.", okText: "OK", {})
        }
    })
}

已授予对照片库的访问权限,但应用程序崩溃并在日志中显示此报告:

2019-08-15 20:25:01.395163+0200 ContactQR[1689:281884] [Animation] +[UIView setAnimationsEnabled:] being called from a background thread. Performing any operation from a background thread on UIView or a subclass is not supported and may result in unexpected and insidious behavior.

代码有什么问题?

来自 PHPhotoLibrary requestAuthorization 的文档:

Photos may call your handler block on an arbitrary serial queue. If your handler needs to interact with user interface elements, dispatch such work to the main queue.

所以需要添加使用DispatchQueue.main.async:

PHPhotoLibrary.requestAuthorization({status in
    DispatchQueue.main.async {
        if status == .authorized {
            let ac = UIActivityViewController(activityItems: [codeImage], applicationActivities: nil)
            self.present(ac, animated: true, completion: nil)
        } else {
            self.showOkAlert(messageTitle: "Access not granted", messageText: "Code image not saved.", okText: "OK", {})
        }
    }
})