0
0
iOS Swiftmobile~15 mins

Share sheet (UIActivityViewController) in iOS Swift - Deep Dive

Choose your learning style9 modes available
Overview - Share sheet (UIActivityViewController)
What is it?
A share sheet is a built-in iOS interface that lets users share content like text, images, or links with other apps or services. It appears as a popup with options such as messaging, email, social media, or saving to files. UIActivityViewController is the class that creates and manages this share sheet in Swift apps. It makes sharing easy without building custom sharing features.
Why it matters
Without the share sheet, apps would need to build their own sharing menus, which is time-consuming and inconsistent. The share sheet provides a familiar, secure, and flexible way for users to share content across apps. It improves user experience by using system-wide sharing options and respects user privacy and preferences.
Where it fits
Before learning this, you should know basic Swift programming and how to create simple iOS user interfaces. After mastering share sheets, you can explore deeper topics like custom activity types, handling share results, and integrating with app extensions.
Mental Model
Core Idea
The share sheet is a system popup that lets users pick how and where to share content from your app, using a simple, standard interface.
Think of it like...
Imagine you have a letter you want to send. Instead of writing different envelopes for each delivery service, you put the letter on a shared desk where the user picks the delivery method they prefer. The share sheet is that shared desk.
┌─────────────────────────────┐
│       Your App Content      │
├─────────────────────────────┤
│      [Share Button]         │
└─────────────┬───────────────┘
              │ Tap
              ▼
┌─────────────────────────────┐
│      Share Sheet Popup      │
│ ┌───────────────┐           │
│ │ Messages      │           │
│ │ Mail          │           │
│ │ Save to Files │           │
│ │ Social Media  │           │
│ └───────────────┘           │
└─────────────────────────────┘
Build-Up - 7 Steps
1
FoundationWhat is UIActivityViewController
🤔
Concept: Introduce the UIActivityViewController as the iOS class for showing the share sheet.
UIActivityViewController is a ready-made controller that displays sharing options for content you provide. You create it with the items to share, then present it on screen. It handles showing all the system and app-provided sharing options automatically.
Result
You get a popup with sharing options without extra coding for each service.
Understanding that UIActivityViewController is a system tool saves you from reinventing sharing features and ensures consistency.
2
FoundationBasic usage with text sharing
🤔
Concept: Learn how to share simple text using UIActivityViewController.
Create a UIActivityViewController with an array containing a string. Present it from your view controller. For example: let text = "Hello from my app!" let activityVC = UIActivityViewController(activityItems: [text], applicationActivities: nil) present(activityVC, animated: true) This shows the share sheet with options to share the text.
Result
The user sees a share sheet popup with apps that can handle text sharing.
Knowing how to share basic content is the first step to enabling user interaction with other apps.
3
IntermediateSharing multiple and different content types
🤔Before reading on: do you think you can share images and URLs together in one share sheet? Commit to yes or no.
Concept: UIActivityViewController can share multiple items of different types at once, like text, images, and URLs.
You can pass an array with mixed content: let text = "Check this out!" let image = UIImage(named: "photo.png")! let url = URL(string: "https://example.com")! let activityVC = UIActivityViewController(activityItems: [text, image, url], applicationActivities: nil) present(activityVC, animated: true) The share sheet adapts to show apps that support these types.
Result
The share sheet shows options that can handle any of the shared items, letting users pick how to share them.
Understanding that the share sheet can handle multiple content types at once makes your app more flexible and user-friendly.
4
IntermediateExcluding unwanted share options
🤔Before reading on: do you think you can hide some share options from the share sheet? Commit to yes or no.
Concept: You can exclude certain system share options to tailor the share sheet to your app's needs.
UIActivityViewController has an excludedActivityTypes property. For example: activityVC.excludedActivityTypes = [.postToFacebook, .print] This hides Facebook posting and printing options from the share sheet.
Result
Users see a cleaner share sheet with only relevant options.
Knowing how to exclude options helps you avoid confusing users with irrelevant choices.
5
IntermediateHandling completion of sharing actions
🤔Before reading on: do you think you can know if the user completed or canceled sharing? Commit to yes or no.
Concept: UIActivityViewController lets you detect when sharing finishes and whether it succeeded or was canceled.
Set the completionWithItemsHandler property: activityVC.completionWithItemsHandler = { activity, completed, items, error in if completed { print("User shared successfully") } else { print("User canceled sharing") } } This helps you respond to user actions.
Result
Your app can react after sharing, like showing a thank you message or logging analytics.
Understanding completion handling lets you improve user experience and track sharing behavior.
6
AdvancedCustom activities and app extensions
🤔Before reading on: do you think you can add your own share options to the share sheet? Commit to yes or no.
Concept: You can create custom share options by defining UIActivity subclasses or using app extensions.
Custom UIActivity subclasses let you add new actions to the share sheet. App extensions allow other apps to provide sharing services. You pass custom activities in the applicationActivities parameter: let customActivity = MyCustomActivity() let activityVC = UIActivityViewController(activityItems: [text], applicationActivities: [customActivity]) This adds your own share option alongside system ones.
Result
Users see your custom share option in the share sheet, enabling unique sharing features.
Knowing how to extend the share sheet empowers you to integrate deeply with your app's ecosystem.
7
ExpertSecurity and privacy considerations in sharing
🤔Before reading on: do you think the share sheet automatically protects user data when sharing? Commit to yes or no.
Concept: The share sheet respects user privacy by sandboxing shared data and limiting what apps can access.
When you share content, the system controls how data is passed to other apps. Apps only get the data you share explicitly. Sensitive data is not leaked. Also, the share sheet UI prevents apps from running code in your app's context. This design protects users and apps from unintended data exposure.
Result
Sharing is safe and respects user privacy without extra work from you.
Understanding the security model helps you trust the share sheet and design sharing flows responsibly.
Under the Hood
UIActivityViewController collects the items you provide and queries the system for all available activities (sharing options) that can handle those data types. It then presents a standardized interface listing these activities. When the user selects one, the system launches the corresponding app or service, passing the shared data securely. The controller manages the lifecycle and user interaction, including completion callbacks.
Why designed this way?
Apple designed UIActivityViewController to unify sharing across apps, avoiding each app building its own sharing UI. This promotes consistency, security, and ease of use. The system controls available activities, so new apps or services can add sharing options without app updates. This modular design balances flexibility with user trust.
┌───────────────────────────────┐
│ Your App                     │
│ ┌─────────────────────────┐ │
│ │ UIActivityViewController │ │
│ └─────────────┬───────────┘ │
└───────────────│─────────────┘
                │
                ▼
┌───────────────────────────────┐
│ System Queries Available Apps  │
│ and Services for Content Types │
└───────────────┬─────────────┘
                │
                ▼
┌───────────────────────────────┐
│ Share Sheet UI Popup           │
│ ┌───────────────┐             │
│ │ User Selects  │             │
│ │ Activity      │             │
│ └───────┬───────┘             │
└─────────│─────────────────────┘
          ▼
┌───────────────────────────────┐
│ Launch Selected App/Service    │
│ Pass Shared Data Securely     │
└───────────────────────────────┘
Myth Busters - 4 Common Misconceptions
Quick: Does UIActivityViewController let you share content silently without user interaction? Commit yes or no.
Common Belief:Some think UIActivityViewController can share content automatically without showing UI.
Tap to reveal reality
Reality:UIActivityViewController always shows the share sheet UI for user confirmation; it does not share silently.
Why it matters:Expecting silent sharing can lead to poor UX or failed sharing attempts, as user consent is required.
Quick: Can you share private app data without preparing it first? Commit yes or no.
Common Belief:People believe they can share any app data directly without formatting or converting it.
Tap to reveal reality
Reality:You must provide shareable data types like strings, images, or URLs; raw private data won't work.
Why it matters:Not preparing data correctly causes sharing to fail or show incorrect content.
Quick: Does excluding activity types guarantee those options never appear anywhere else? Commit yes or no.
Common Belief:Excluding activity types removes them globally from the device.
Tap to reveal reality
Reality:Excluding only hides them in your app's share sheet instance; other apps still show them.
Why it matters:Misunderstanding this can cause confusion about share sheet behavior across apps.
Quick: Can you detect exactly which app the user shared to? Commit yes or no.
Common Belief:Some think you can always know the exact app chosen by the user.
Tap to reveal reality
Reality:You get the activity type identifier, but not always the exact app name or details.
Why it matters:Expecting full app info can lead to privacy issues or incorrect analytics.
Expert Zone
1
Custom UIActivity subclasses must carefully manage memory and UI to avoid leaks or crashes during sharing.
2
The order of activity items affects how some services interpret shared content, so ordering matters.
3
Completion handlers may be called on background threads; updating UI requires dispatching to the main thread.
When NOT to use
Avoid UIActivityViewController when you need fully custom sharing workflows or background sharing without user interaction. Instead, use direct APIs like Social framework, custom network calls, or app extensions for specialized sharing.
Production Patterns
Apps often combine UIActivityViewController with analytics to track sharing behavior, exclude irrelevant options per context, and provide custom activities for app-specific features like saving to proprietary cloud storage.
Connections
Intent system (Android)
Similar pattern
Both iOS share sheet and Android intents provide a system-managed way to share data between apps, promoting consistency and security.
Command pattern (software design)
Builds-on
UIActivityViewController uses the command pattern by encapsulating sharing actions as objects (activities) that can be executed, making the system extensible.
Human-computer interaction (HCI)
Builds-on
The share sheet is a practical example of HCI principles, providing a consistent, discoverable, and user-friendly interface for cross-app communication.
Common Pitfalls
#1Trying to share unsupported data types directly.
Wrong approach:let data = MyCustomObject() let activityVC = UIActivityViewController(activityItems: [data], applicationActivities: nil) present(activityVC, animated: true)
Correct approach:let text = "Data description" let activityVC = UIActivityViewController(activityItems: [text], applicationActivities: nil) present(activityVC, animated: true)
Root cause:UIActivityViewController only supports standard shareable types; custom objects must be converted to supported formats.
#2Not setting excludedActivityTypes when irrelevant options confuse users.
Wrong approach:let activityVC = UIActivityViewController(activityItems: [text], applicationActivities: nil) present(activityVC, animated: true)
Correct approach:let activityVC = UIActivityViewController(activityItems: [text], applicationActivities: nil) activityVC.excludedActivityTypes = [.print, .assignToContact] present(activityVC, animated: true)
Root cause:Ignoring excludedActivityTypes leads to cluttered share sheets and poor user experience.
#3Updating UI directly inside completionWithItemsHandler without dispatching to main thread.
Wrong approach:activityVC.completionWithItemsHandler = { _, completed, _, _ in if completed { self.statusLabel.text = "Shared!" } }
Correct approach:activityVC.completionWithItemsHandler = { _, completed, _, _ in DispatchQueue.main.async { if completed { self.statusLabel.text = "Shared!" } } }
Root cause:Completion handler may run on background thread; UI updates must be on main thread.
Key Takeaways
UIActivityViewController provides a simple, consistent way to share content across iOS apps using a system-managed share sheet.
You can share multiple types of content at once and customize which sharing options appear to users.
Handling completion lets your app respond to user actions after sharing, improving experience and analytics.
The share sheet respects user privacy and security by controlling data flow and sandboxing shared content.
Advanced use includes creating custom share options and understanding threading and memory nuances for robust apps.