Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tekkub/17e37d6344c2637e56f82025929caef8 to your computer and use it in GitHub Desktop.
Save tekkub/17e37d6344c2637e56f82025929caef8 to your computer and use it in GitHub Desktop.
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