Sharing via UIActivityViewController to Twitter/Facebook etc. causing crash

后端 未结 5 1187
野的像风
野的像风 2020-12-06 02:10

On iOS8 I\'m using a UIActivityViewController to share a UIImage to Facebook/Twitter etc. It seemed to be working fine, but today it suddenly started crashing when running t

5条回答
  •  执笔经年
    2020-12-06 02:44

    Swift 5 - Copy from Working Project

    Problem

    If you present UIActivityViewController for sharing in the following way, your app will work correctly but it will crash on iPad devices.

    func shareSiteURL()
    {
        let title = "My app"
        let url = URL(string: "https://myWebSite.com")
    
        let activityController = UIActivityViewController(activityItems: [url!, title], applicationActivities: nil)
        self.present(activityController, animated: true, completion: nil)
    }
    

    Explanation

    When you presented UIActivityViewController on the iPad, the iPad presents the activity controller as a popover controller and hence it needs to know and use the source view. On the previous code, we did not pass the source view in case if the device is an iPad and that is why the app crashed when running on iPad.

    Solution

    To solve this issue, we are going to check if the controller is presented as a popover (the app is running on iPad) and if so, we will pass the source view otherwise the app will crash.

    func shareSiteURL()
    {
        let title = "My app"
        let url = URL(string: "https://myWebSite.com")
    
        // check if the controller is presented as a popover (the app is running on iPad)
        // and if so, we will pass the source view otherwise the app will crash.
    
        if let popoverController = activityController.popoverPresentationController
        {
            popoverController.sourceView = viewController.view
        }
    
        let activityController = UIActivityViewController(activityItems: [url!, title], applicationActivities: nil)
        self.present(activityController, animated: true, completion: nil)
    }
    

提交回复
热议问题