UIActivityViewController provides convenient access to various services such as sending items via email or SMS, copying items to the pasteboard, posting content to social media sites. Let’s make a demo to show how to use it.
For simplicity, just use a button to trigger the services of
Run the app, tap the button
Choose Mail, we can see the contents are just the two items we used to initialize the
Well, above is the least we should know to use
UIActivityViewController, and of course there’s much more about this topic.
If you don’t want Mail to show up in the activity sheet, specify it by setting
excludedActivityTypes, like this:
Run the app to see the effect:
If you want to forbid more, just seperate them with comma. You can see all built-in activity types here.
It is evident that you want to use your own class as the item, then you should make it conform to
<UIActivityItemSource>. An example is below:
Correspondingly, initialization of
UIActivityViewController changes to
You may wonder what the method
activityViewControllerPlaceholderItem(_:) is used for.
This method provides a “promise” to
UIActivityViewController what the
itemForActivityType will be . The class type of the return value is used to figure out what activities to offer in the activity sheet (reference). In the example above, I return a
String, so the activity sheet is identical to the very first
screenshot. If I cheat
UIActivityViewController like this:
The activity sheet will be as below:
The control flow in
activityViewController(_:itemForActivityType:) is not necessary, you can just return something directly if you don’t need to customize your item according to different activity type.
For deeper understanding and best practice of
UIActivityViewController, I highly recommand this blog.
The demo project is here.