UIActivityViewController (Share Controller) in few lines of code (Swift)

In most of the applications we have to share the app link or text or images, so we use this UIActivityViewController to share the data to multiple apps.

Akshay Somkuwar

--

We will be sharing text in this post but you can do the same with other media types..i will be adding it in this post soon.

#Step 1:

Create a variable to hold the text you want to share like let shareText = "This will be your share text"

#Step 2:

Create a viewControllerObject of type UIActivityViewController() and add the text in activityItems array

let vc = UIActivityViewController(activityItems: [shareText], applicationActivities: nil)

#Step 3:

And at last present this viewController

present(vc, animated: true, completion: nil)

#Step 4:

This code will crash if you run this on iPad because of the present viewController,
To fix this we will add this code.

if let popOver = vc.popoverPresentationController {
popOver.sourceView = view
popOver.sourceView?.center = view.center
}

Result will look like this

Thank you for reading 🙏

Sign up to discover human stories that deepen your understanding of the world.

--

--

Akshay Somkuwar
Akshay Somkuwar

Written by Akshay Somkuwar

iOS | MacOS | React Native Developer..

Responses (1)

Write a response