Search code examples
swiftxcodeuiactivityviewcontroller

App crashes when presenting UIActivityController in iPad


I have create a view in my app and once a button is clicked the UIActivityController should popup on screen. however, the app crashes only on iPad but on iPhone it is working fine. Anyone knows whats this behavior and how to fix it? this is the code im using:

@IBAction func send(_ sender: AnyObject)
{        
    var image: UIImage!
    image = UIImage(named: "image.png")
    var urlfinal:NSURL!
    urlfinal =  URL.init(string:url as String)! as NSURL
    let items = [mytitle , image , urlfinal] as [Any]


    let controller = UIActivityViewController(activityItems: items, applicationActivities: .none)

    controller.popoverPresentationController?.barButtonItem = sender as? UIBarButtonItem

    self.present(controller, animated: true, completion: nil)
}

this is the error in the console im getting:

Terminating app due to uncaught exception 'NSGenericException', reason: 'UIPopoverPresentationController () should have a non-nil sourceView or barButtonItem set before the presentation occurs.'


Solution

  • As the error suggests, you need to add a sourceView to your popoverPresentationController.

    controller.popoverPresentationController?.sourceView = sender as! UIView