Search code examples
iosipadswiftuipopovercontrolleruiactivityviewcontroller

UIActivity activityViewController crash on iPad in Swift


I have the following code below to toggle UIActivityViewController

@IBAction func shareButtonClicked(sender: UIButton)
{
    let textToShare = "Text"

    if let myWebsite = NSURL(string: "http://www.example.com/")
    {
        let objectsToShare = [textToShare, myWebsite]
        let activityVC = UIActivityViewController(activityItems: objectsToShare, applicationActivities: nil)

        self.presentViewController(activityVC, animated: true, completion: nil)
    }
}

But it crashes on iPad. How do I present it modally in Swift?


Solution

  • It will crash because in iPad you can not present UIActivityViewController as like in iPhone.

    You need to present it in a popover as per the design guidelines suggested by Apple.

    The below code will demonstrate how to show present it in a UIPopoverPresentationController.

    @IBAction func shareButtonClicked(sender: UIButton)
    {
        let textToShare = "Text"
    
        if let myWebsite = NSURL(string: "http://www.example.com/")
        {
            let objectsToShare = [textToShare, myWebsite]
            let activityVC = UIActivityViewController(activityItems: objectsToShare, applicationActivities: nil)
    
            var nav = UINavigationController(rootViewController: activityVC)
            nav.modalPresentationStyle = UIModalPresentationStyle.Popover
            var popover = nav.popoverPresentationController as UIPopoverPresentationController!
            activityVC.preferredContentSize = CGSizeMake(500,600)
            popover.sourceView = self.view
            popover.sourceRect = CGRectMake(100,100,0,0)
    
            self.presentViewController(nav, animated: true, completion: nil)
    
        }
    }
    

    Note: Extend your view controller with UIPopoverPresentationController delegate.

    For example:

    class MyViewController : UIViewController, UIPopoverPresentationControllerDelegate {
    //........
    }