Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Share Sheet UIActivityViewController within SwiftUI
import SwiftUI
struct ContentView: View {
var body: some View {
VStack {
Text("Hello, world!")
.padding()
.shareSheet(items: ["Hello world!"])
Text("Hello, world!")
.padding()
.shareSheet(items: ["Hello world!"], excludedActivityTypes: [.postToFacebook])
// OR
Text("Hello, world!")
.padding()
.modifier(ShareSheetModifer(shareSheetItems: ["Hello, world!"]))
Text("Hello, world!")
.padding()
.modifier(ShareSheetModifer(shareSheetItems: ["Hello, world!"],
excludedActivityTypes: [.postToFacebook]))
}
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
struct ShareSheetModifer: ViewModifier {
@State private var showShareSheet: Bool = false
@State var shareSheetItems: [Any] = []
var excludedActivityTypes: [UIActivity.ActivityType]? = nil
func body(content: Content) -> some View {
content
.contextMenu {
Button(action: {
self.showShareSheet.toggle()
}) {
Text("Share")
Image(systemName: "square.and.arrow.up")
}
}
.sheet(isPresented: $showShareSheet, content: {
ActivityViewController(activityItems: self.$shareSheetItems, excludedActivityTypes: excludedActivityTypes)
})
}
}
struct ActivityViewController: UIViewControllerRepresentable {
@Binding var activityItems: [Any]
var excludedActivityTypes: [UIActivity.ActivityType]? = nil
func makeUIViewController(context: UIViewControllerRepresentableContext<ActivityViewController>) -> UIActivityViewController {
let controller = UIActivityViewController(activityItems: activityItems,
applicationActivities: nil)
controller.excludedActivityTypes = excludedActivityTypes
return controller
}
func updateUIViewController(_ uiViewController: UIActivityViewController, context: UIViewControllerRepresentableContext<ActivityViewController>) {}
}
extension View {
func shareSheet(items: [Any], excludedActivityTypes: [UIActivity.ActivityType]? = nil) -> some View {
self.modifier(ShareSheetModifer(shareSheetItems: items, excludedActivityTypes: excludedActivityTypes))
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment