How do I create share sheets and custom activities on iOS using Swift?

In iOS, share sheets are a common way to allow users to share content from your app to other apps. You can create custom activities to extend the sharing capabilities of your application.

Creating Share Sheets and Custom Activities on iOS using Swift

Here’s a basic example of how to create a share sheet in Swift and implement a custom activity.

1. Creating a Share Sheet

To create a share sheet in your app, you can use the UIActivityViewController. Here’s how you can do it:

let textToShare = "Check out this awesome content!" let activityViewController = UIActivityViewController(activityItems: [textToShare], applicationActivities: nil) // Present the share sheet present(activityViewController, animated: true, completion: nil)

2. Creating a Custom Activity

To create a custom activity, you can subclass UIActivity. Here's an example:

class CustomActivity: UIActivity { override var activityType: UIActivity.ActivityType? { return UIActivity.ActivityType("com.example.CustomActivity") } override var activityTitle: String? { return "Custom Share" } override var activityImage: UIImage? { return UIImage(systemName: "star") // Replace with your custom image } override func prepare(withActivityItems activityItems: [Any]) { // Prepare data to share } override func perform() { // Handle the sharing process activityDidFinish(true) } }

Now you can include your custom activity in the share sheet as follows:

let customActivity = CustomActivity() let activityViewController = UIActivityViewController(activityItems: [textToShare], applicationActivities: [customActivity]) // Present the share sheet with custom activity present(activityViewController, animated: true, completion: nil)

iOS Swift Share Sheets UIActivityViewController Custom Activities