Search code examples
iosiphoneswiftipad

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
        textView.resignFirstResponder()
        // 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
            displayShareSheet(textView.text!)
        }
    }
    // 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)
        return
    }
    // Display Share Sheet
    func displayShareSheet(shareContent:String) {
        let activityViewController = UIActivityViewController(activityItems: [shareContent as NSString], applicationActivities: nil)
        presentViewController(activityViewController, animated: true, completion: {})

    }

Solution

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

    if let popoverPresentationController = activityController.popoverPresentationController {
         popoverPresentationController.sourceView = self.view
         popoverPresentationController.sourceRect = CGRect(x: CGRectGetMidX(view.bounds), y: CGRectGetMidY(view.bounds), width: 0, height: 0)
         popoverPresentationController.permittedArrowDirections = UIPopoverArrowDirection.init(rawValue: 0) //Removes arrow as I dont want it
    }
    

    Line 1 sets the source view.

    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.

    Hope this helps