On iOS8 I\'m using a UIActivityViewController to share a UIImage to Facebook/Twitter etc. It seemed to be working fine, but today it suddenly started crashing when running t
If you present UIActivityViewController
for sharing in the following way, your app will work correctly but it will crash on iPad devices.
func shareSiteURL()
{
let title = "My app"
let url = URL(string: "https://myWebSite.com")
let activityController = UIActivityViewController(activityItems: [url!, title], applicationActivities: nil)
self.present(activityController, animated: true, completion: nil)
}
When you presented UIActivityViewController
on the iPad, the iPad presents the activity controller as a popover controller and hence it needs to know and use the source view. On the previous code, we did not pass the source view in case if the device is an iPad and that is why the app crashed when running on iPad.
To solve this issue, we are going to check if the controller is presented as a popover (the app is running on iPad) and if so, we will pass the source view otherwise the app will crash.
func shareSiteURL()
{
let title = "My app"
let url = URL(string: "https://myWebSite.com")
// check if the controller is presented as a popover (the app is running on iPad)
// and if so, we will pass the source view otherwise the app will crash.
if let popoverController = activityController.popoverPresentationController
{
popoverController.sourceView = viewController.view
}
let activityController = UIActivityViewController(activityItems: [url!, title], applicationActivities: nil)
self.present(activityController, animated: true, completion: nil)
}