Search code examples
iosswiftuiactivityviewcontroller

Sharing different content based on selected activity - UIActivityController


Currently I am sending a Image and a text whenever the user wants to share the image using UIActivityController. This works fine on email and gmail , but its gets messed up for whatsapp or Skype(Only the text is sent). So what I would like to do is share image url and text if the user selects activity as whatsapp or Skype. Is this possible?

I searched for this problem , and found that you should sub class UIActivityItemProvider and implement the methods of UIActivityItemSource which I did, but I am unable to get callbacks for the implemented methods.

I have implemented these methods activityViewControllerPlaceholderItem: and activityViewController:itemForActivityType: but I don't receive a callback.


Solution

  • Just make a subclass of UIActivityItemProvider and override item property to give your custom activity items, i.e.

    class CustomActivityItemProvider: UIActivityItemProvider
    {
        override var item: Any{
            switch self.activityType!
            {
            case UIActivityType.postToFacebook:
                return "Hello"
            default:
                return "Whatever"
            }
        }
    }
    

    Using it:

    let activityItem = CustomActivityItemProvider(placeholderItem: "")
    let activityViewController = UIActivityViewController(activityItems: [activityItem], applicationActivities: nil)
    self.present(activityViewController, animated: true, completion: nil)
    

    Also, you can customize only those UIActivityType, that are exposed by Apple for use by developers. For UIActivityTypes refer to: https://developer.apple.com/documentation/uikit/uiactivitytype