How to Implement Share Sheet in SwiftUI

The Share Sheet is a powerful tool that allows users to share content from your app with others through a variety of methods such as social media, email, or messaging. 

In this tutorial, you will learn how to add a Share Sheet to your SwiftUI app, allowing users to easily share content with others. You will also learn how to customize the Share Sheet to fit the needs of your app.

..

Showing a share sheet in your SwiftUI application requires only a few lines of code and is so easy to implement.

Share Sheet - Call Apple's share sheet when the user clicks on a button.

Create your button

First, create your button using the Share button from SF Symbols.

Button(action: shareButton) {
	Image(systemName: "square.and.arrow.up")
			.foregroundColor(.black)
}

..

Create the function

Finally, create the function to show or hide your share sheet when the user clicks on the share button.

func shareButton() {		
		let url = URL(string: "https://www.swiftuiio.com/")
		let activityController = UIActivityViewController(activityItems: [url!], applicationActivities: nil)

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

..

It's as simple as that! Now, when a user clicks on the share button, it'll show a share sheet just like the image above.

Comments