I wrote this code to share 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", {})
}
})
}
Access to Photo Library is granted but app crashes with this report in log:
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.
What's wrong in the code?
From the documentation for 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.
So you need to add the use of 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", {})
}
}
})