iap-Software iap-Software -5 years ago 194
Swift Question

Share Sheet Crashing on iPad

I'm creating a share sheet where someone can share the text from a text field. I've got it working on the iPhone, but the app crashes on the iPad. I know that it has to be in a popover form and have had this issue back in the day of Objective-C, but I can't seem to figure it out on Swift. This is my code that I've got going for the share sheet:

@IBAction func myShareButton(sender: AnyObject) {
// Hide the keyboard
// Check and see if the text field is empty
if (textView.text == "") {
// The text field is empty so display an Alert
displayAlert("Warning", message: "You haven't written anything yet!")
} else {
// We have contents so display the share sheet
// Show Warning
func displayAlert(title: String, message: String) {
let alertController = UIAlertController(title: title, message: message, preferredStyle: .Alert)
alertController.addAction(UIAlertAction(title: "OK", style: .Default, handler: nil))
presentViewController(alertController, animated: true, completion: nil)
// Display Share Sheet
func displayShareSheet(shareContent:String) {
let activityViewController = UIActivityViewController(activityItems: [shareContent as NSString], applicationActivities: nil)
presentViewController(activityViewController, animated: true, completion: {})


Answer Source

I implemented share sheets today as well and had the exact same issue. You need to add this before presenting.

activityViewController.popoverPresentationController?.sourceView = self.view
activityViewController.popoverPresentationController?.sourceRect = CGRect(x: CGRectGetMidX(view.bounds), y: CGRectGetMidY(view.bounds), width: 0, height: 0)
activityViewController.popoverPresentationController?.permittedArrowDirections = UIPopoverArrowDirection.init(rawValue: 0) //.Down

Line 1 is the one you need to stop the crash

Line 2 I use to Center the popover right in the middle (I use it in SpriteKit and the popover is not attached to anything)

Line 3 I use to remove the arrow as I don't want it.

There is one more line to optionally use

activityViewController.barButtonItem = 

which I am not using so not 100% what it does.

Hope this helps

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download