How to create a simple Share Sheet (UIActivityViewController) in SwiftUI

Jeeva Tamilselvan
2 min readJul 25, 2020
share sheet — iOS

On many scenarios, We have used this share sheets in iPhone. Mostly,

  1. Airdrop something to a nearby person.
  2. Send something via iMessage, Whatsapp or Mail.

How to achieve this in SwiftUI? Let’s learn this 👨‍💻

To create a Share sheet we have to do 3 simple steps,

  1. Get the data you want to share
  2. Create a UIActivityViewController object and attach the data with this
  3. Present the UIActivityViewController

Step 1:

guard let data = URL(string: “https://www.zoho.com") else { return }

Here, we have created an URL. This is the data we are going to share using the share sheet.

Step 2:

let av = UIActivityViewController(activityItems: [data], applicationActivities: nil)

Now, we have created a UIActivityViewController object. Here, we need to pass the data we need to share in the activityItems: argument.

activityItems: [Any] is an array which accepts any data type.

Step 3:

UIApplication.shared.windows.first?.rootViewController?.present(av, animated: true, completion: nil)

In the last step, we are finding the current window and present the UIActivityViewController which we have created in the previous step.

Here UIApplication.shared.windows.first?.rootViewController? will give us the control of current working view controller.

Conclusion:

Let’s put this in a function and call it will a button action, So the final code will be like below,

And the output will be like this,

Thank you 🙏

--

--