How to present UIActivityViewController on iPhone and iPad
1 min readDec 19, 2017
Presenting UIActivityViewController to share items from your iOS app is a simple enough task.
let activityVC = UIActivityViewController(activityItems: ["String to share"], applicationActivities: nil)present(activityVC, animated: true, completion: nil)
Presenting UIActivityViewContoller modally works wells on iPhone:
However this results in a crash on iPad:
*** Terminating app due to uncaught exception ‘NSGenericException’, reason: ‘Your application has presented a UIActivityViewController (<UIActivityViewController: 0x7f829b854600>). In its current trait environment, the modalPresentationStyle of a UIActivityViewController with this style is UIModalPresentationPopover. You must provide location information for this popover through the view controller’s popoverPresentationController. You must provide either a sourceView and sourceRect or a barButtonItem. If this information is not known when you present the view controller, you may provide it in the UIPopoverPresentationControllerDelegate method -prepareForPopoverPresentation.’
The error message is self explanatory. UIActivityViewController is presented in a popover on iPad. Even documentations mentions this
On iPad, you must present the view controller in a popover.
Therefore, on iPad, you must configure `popoverPresentationController` by providing either a sourceView and sourceRect or a barButtonItem.
let activityVC = UIActivityViewController(activityItems: ["String to share"], applicationActivities: nil)present(activityVC, animated: true, completion: nil)
if let popOver = activityVC.popoverPresentationController {
popOver.sourceView = self.view
//popOver.sourceRect =
//popOver.barButtonItem
}