I have these protocol methods,
activityViewControllerPlaceholderItem:
and activityViewController:itemForActivityType:
but they never get called. How do I tell the UIActivityViewController
to call them?
I also have an UIActivityItemProvider
subclass, however I'm confused as to who calls these 2 methods. I'd really appreciate some sample code, as I can't find anything on the web. :)
According to the documentation. The array of activity items that you pass to
-initWithActivityItems:applicationActivities:
can be an array of data objects, like strings or images, or it can be array of objects that implement theUIActivityItemSource
protocol.If you pass an array of objects that implement the
UIActivityItemSource
protocol then your instance ofUIActivityViewController
will call those methods on your activity items. Those objects do not necessarily have to be subclasses ofUIActivityItemProvider
.UIActivityItemProvider
is just a class that conforms to this protocol.Piggybagging off of what JotWee and Sihad Begovic had provided, here's the Swift 5.0 version of making your
ViewController
adopts theUIActivityItemSource
protocol and usingshare
barButtonItem to trigger the sharing of objects with other apps on your iPhone(s), and or, iPad(s):Inside the
viewDidLoad
method of yourViewController
class, implement the following:And somewhere outside your
viewDidLoad
method, but inside yourViewController
class, let us implement theshareBarButtonItemClicked
method as below:Now here's where things gets interesting. We need to make your
ViewController
class conform to theUIActivityItemSource
protocol and implement its required methods as below:And that's how you adopt your class to conform to the UIActivityItemSource protocol and implement its methods. For more readings, I find this web article from HackingWithSwift website very really insightful.
Happy coding!
The answer by JotWee helped me out.
There is no need for sub classing,
UIActivityItemSource
protocol methods can be implemented in view controller where share button is implemented.Very important to add
self
in activity items array, like this (as JotWee suggested):Here is my final implementation:
ViewController.h
ViewController.m
You can implement the protocol wherever you want, even your viewcontroller is fine. Just instantiate the activityViewController with
initWithActivityItems:@[self]
.