How to create a simple Share Sheet (UIActivityViewController) in SwiftUI
On many scenarios, We have used this share sheets in iPhone. Mostly,
- Airdrop something to a nearby person.
- 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,
- Get the data you want to share
- Create a UIActivityViewController object and attach the data with this
- 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 🙏