1

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?

rmaddy
  • 314,917
  • 42
  • 532
  • 579
Dawy
  • 770
  • 6
  • 23

1 Answers1

1

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", {})
        }
    }
})

rmaddy
  • 314,917
  • 42
  • 532
  • 579
  • Error disappeared but image is not saved if it is taken from imgQRCode UIImageView but if I use let codeImage = UIImage(named: "Ghost") insteag than it works. – Dawy Aug 15 '19 at 19:43
  • You should post a new question specific to your new issue with all relevant details if you are unable to figure it out on your own. – rmaddy Aug 15 '19 at 19:49