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

Image for post
Image for post
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

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.

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.

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.

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,

Image for post
Image for post

Thank you 🙏

Written by

Automation QA Engineer by profession. Learning iOS Development.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store