Search code examples
iosxcodeipaduipopovercontrolleruiactivityviewcontroller

UIActivityViewController in a PopOverViewController Crashing in Swift


I have a UIActivityViewController for a share button. For iPhone I have it as a regular UIActivityViewController and for iPad its in a PopOverViewController. This is the code I have for it

let textToShare = "Check out this website!"

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

   if let popUpVC = activityVC.popoverPresentationController {
      popUpVC.permittedArrowDirections = .Any
      popUpVC.sourceRect = share.frame
   }
   self.view?.window?.rootViewController?.presentViewController(activityVC, animated: true, completion: nil)
}

When I press the share button on a iPad it just crashes with a (lldb). But when I have it present from a view it works but isn't in the right position. This is the code I am using for the present from a view.

popUpVC.sourceView = self.view

Solution

  • Try this, you have to check if the device you are currently running on responds to popoverPresentationController because popoverPresentationController is new to iOS 8 and will crash on iOS 7. It'll also be nil on iPhone because it's only in a UIPopover on iPad.

    let activityViewController = UIActivityViewController(activityItems: [myText, myUrl], applicationActivities: nil)
    
    if activityViewController.respondsToSelector("popoverPresentationController") {
       // iOS8+
       view.presentViewController(activityViewController, animated: true, completion: nil)
       activityViewController.popoverPresentationController?.sourceView = view
    } else {
       view.presentViewController(activityViewController, animated: true, completion: nil)
    }