UIActivityViewController
UIActivityViewController
is a UIKit class that provides a system interface for sharing content from an iOS app to other apps, services, or actions like copying, printing, or saving. Introduced in iOS 6, it simplifies the process of presenting a standardized share sheet to users.
Purpose
- Sharing Content: Enables users to share text, images, URLs, or other data via built-in services (e.g., Messages, Mail, AirDrop) or third-party apps.
- Extensibility: Supports custom activities for app-specific sharing options.
- User-Friendly: Presents a consistent, native share sheet tailored to the device and available services.
Key Features
- Activity Items: Supports various data types (e.g.,
String
,URL
,UIImage
,Data
) as shareable content. - Application Activities: Allows developers to add custom sharing options.
- Excluded Activities: Lets developers exclude specific system activities (e.g., exclude AirDrop or Copy).
- Presentation: Integrates with UIKit for modal presentation or popover on iPad.
- Completion Handling: Provides a completion handler to track the outcome of the share action.
Basic Usage
UIActivityViewController
is initialized with an array of activity items and optional application activities, then presented as a modal view controller.
Example
import UIKit
// Prepare content to share
let text = "Check out this link!"
let url = URL(string: "https://example.com")!
let image = UIImage(named: "sampleImage")!
let activityItems: [Any] = [text, url, image]
// Initialize UIActivityViewController
let activityViewController = UIActivityViewController(activityItems: activityItems, applicationActivities: nil)
// Present the share sheet
present(activityViewController, animated: true, completion: nil)
Key Points
- Initialization: Use
UIActivityViewController(activityItems:applicationActivities:)
to set up the share sheet. - Activity Items: Provide an array of shareable items; the system determines which activities support each item.
- Presentation: Present modally on iPhone or as a popover on iPad using
popoverPresentationController
.
Advanced Features
Excluding Activities
Exclude specific system activities using excludedActivityTypes
:
activityViewController.excludedActivityTypes = [.airDrop, .copyToPasteboard, .print]
Custom Activities
Create custom activities by subclassing UIActivity
:
class CustomActivity: UIActivity {
override var activityType: UIActivity.ActivityType? {
return .init("com.example.customActivity")
}
override var activityTitle: String? {
return "Custom Share"
}
override var activityImage: UIImage? {
return UIImage(systemName: "star.fill")
}
override func canPerform(withActivityItems: [Any]) -> Bool {
return true // Check if activity supports items
}
override func perform() {
// Implement custom share logic
print("Performing custom share")
activityDidFinish(true)
}
}
// Add custom activity
let customActivity = CustomActivity()
let activityViewController = UIActivityViewController(activityItems: activityItems, applicationActivities: [customActivity])
Completion Handler
Track the outcome of the share action using a completion handler:
activityViewController.completionWithItemsHandler = { activityType, completed, returnedItems, error in
if completed {
print("Shared via \(activityType?.rawValue ?? "unknown")")
} else if let error = error {
print("Share failed: \(error.localizedDescription)")
} else {
print("Share cancelled")
}
}
Popover Configuration (iPad)
For iPad, configure the popover source to anchor the share sheet:
if let popoverController = activityViewController.popoverPresentationController {
popoverController.sourceView = view // The view to anchor the popover
popoverController.sourceRect = CGRect(x: view.bounds.midX, y: view.bounds.midY, width: 0, height: 0)
popoverController.permittedArrowDirections = .any
}
Activity Item Providers
For dynamic or type-specific sharing, use UIActivityItemProvider
to customize data per activity:
class CustomItemProvider: UIActivityItemProvider {
override func activityViewController(_ controller: UIActivityViewController, itemForActivityType activityType: UIActivity.ActivityType?) -> Any? {
if activityType == .postToTwitter {
return "Short text for Twitter"
}
return placeholderItem // Default item
}
}
let itemProvider = CustomItemProvider(placeholderItem: "Default text")
let activityViewController = UIActivityViewController(activityItems: [itemProvider], applicationActivities: nil)
Best Practices
- Content Selection: Provide only relevant activity items to avoid overwhelming users.
- Device Compatibility: Test on iPhone and iPad, ensuring proper popover configuration for iPad.
- Custom Activities: Use sparingly to avoid cluttering the share sheet.
- Accessibility: Ensure shared content is accessible (e.g., provide alt text for images).
- Error Handling: Use the completion handler to log or handle errors gracefully.
Limitations
- System Dependency: Available activities depend on the device’s configuration (e.g., AirDrop requires hardware support).
- Customization: Limited control over the share sheet’s appearance, as it’s a system UI.
- Backward Compatibility: Available since iOS 6, but some features (e.g., item providers) require newer iOS versions.
Summary
UIActivityViewController
is a versatile tool for enabling content sharing in iOS apps, supporting a wide range of system and custom activities. It simplifies integration with native services like Messages, Mail, and AirDrop while allowing developers to extend functionality with custom activities and item providers. Proper configuration ensures a seamless user experience across devices.