I was encountering this exact problem recently (the original question) in Swift 2.0, where UIActivityViewController
worked fine for iPhones, but caused crashes when simulating iPads.
I just want to add to this thread of answers here that, at least in Swift 2.0, you don't need an if statement. You can just make the popoverPresentationController
optional.
As a quick aside, the accepted answer appears to be saying that you could have just a sourceView, just a sourceRect, or just a barButtonItem, but according to Apple's documentation for UIPopoverPresentationController you need one of the following:
- barButtonItem
- sourceView and sourceRect
The particular example I was working on is below, where I am creating a function that takes in a UIView
(for the sourceView and sourceRect) and String
(the UIActivityViewController's sole activityItem).
func presentActivityViewController(sourceView: UIView, activityItem: String ) { let activityViewController = UIActivityViewController(activityItems: [activityItem], applicationActivities: []) activityViewController.popoverPresentationController?.sourceView = sourceView activityViewController.popoverPresentationController?.sourceRect = sourceView.bounds self.presentViewController(activityViewController, animated: true, completion: nil) }
This code works on iPhone and iPad (and even tvOS I think) -- if the device does not support popoverPresentationController
, the two lines of code that mention it are essentially ignored.
Kinda nice that all you need to do to make it work for iPads is just add two lines of code, or just one if you're using a barButtonItem!