Sharing button works perfectly on iPhone but crash on iPad

北战南征 提交于 2020-07-23 17:30:06

问题


I'm trying to add a button in order to share some sentences in Twitter, Facebook... etc. It all works on all iPhone models but simulator crash with an iPad.

This is my code:

@IBAction func shareButton(sender: AnyObject) {

    frase = labelFrases.text!
    autor = labelAutores.text!


    var myShare = "\(frase) - \(autor)"

    let activityVC: UIActivityViewController = UIActivityViewController(activityItems: [myShare], applicationActivities: nil)



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

And this is the error:

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

How should I solve it? Thanks


回答1:


For ipad (iOS > 8.0) you need to set popoverPresentationController:

    //check ipad
    if (UIDevice.currentDevice().userInterfaceIdiom == UIUserInterfaceIdiom.Pad)
    {
        //ios > 8.0
        if ( activityVC.respondsToSelector(Selector("popoverPresentationController")) ) {
            activityVC.popoverPresentationController?.sourceView = super.view
        }
    }

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

More information here: UIActivityViewController crashing on iOS8 iPads




回答2:


Do this instead for Swift 5 to get share button working on both iPad and iPhone:

   @IBAction func shareButton(sender: UIButton) { {
    let itemToShare = ["Some Text goes here"]
    let avc = UIActivityViewController(activityItems: itemToShare, applicationActivities: nil)

    //Apps to be excluded sharing to
    avc.excludedActivityTypes = [
        UIActivityType.print,
        UIActivityType.addToReadingList
    ]
    // Check if user is on iPad and present popover
    if UIDevice.current.userInterfaceIdiom == .pad {
        if avc.responds(to: #selector(getter: UIViewController.popoverPresentationController)) {
            avc.popoverPresentationController?.barButtonItem = sender
        }
    }
    // Present share activityView on regular iPhone
    self.present(avc, animated: true, completion: nil)
}

Hope this helps!



来源:https://stackoverflow.com/questions/31506081/sharing-button-works-perfectly-on-iphone-but-crash-on-ipad

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!