Solved: ShareSheet: UIViewControllerRepresentable

Sure, let’s dive into the topic of ShareSheet usage in Swift.

Swift, the powerful and intuitive programming language for macOS, iOS, watchOS, and many other OS, has always been the first choice among the developers for Apple apps. One incredibly useful utility in Swift is the ShareSheet, when your app needs to share some data, like text, images, URLs, etc., with other apps.

“`swift
let av = UIActivityViewController(activityItems: items, applicationActivities: nil)
present(av, animated: true)
“`

But the UIKit’s version of the ShareSheet may not fit well in a SwiftUI interface. This is where UIViewControllerRepresentable comes in. It provides a way to wrap UIKit view controllers and make them available to SwiftUI layouts. Pairing this with ShareSheet, the problem is ingeniously solved.

Understanding UIViewControllerRepresentable

UIViewControllerRepresentable is a protocol to wrap UIKit view controllers and use them in SwiftUI. By using UIViewControllerRepresentable, a UIKit view controller can be managed and used just like a SwiftUI view.

Here is a step-by-step tutorial of how to use UIViewControllerRepresentable with UIActivityViewController to present a share sheet in SwiftUI.

1. Define a structure that conforms to UIViewControllerRepresentable protocol:

“`swift
struct ActivityViewController: UIViewControllerRepresentable {
var items: [Any]

}
“`

2. Implement its two methods:

“`swift
struct ActivityViewController: UIViewControllerRepresentable {
var items: [Any]

// 1
func makeUIViewController(context: UIViewControllerRepresentableContext) -> UIActivityViewController {
let controller = UIActivityViewController(activityItems: items, applicationActivities: nil)
return controller
}

// 2
func updateUIViewController(_ uiViewController: UIActivityViewController, context: UIViewControllerRepresentableContext) {}
}
“`

3. Use in SwiftUI View:

“`swift
struct ContentView: View {
var body: some View {
Button(action: {
UIApplication.shared.windows.first?.rootViewController?.present(UIHostingController(rootView: ActivityViewController(items: [“Share this text”])), animated: true)
}) {
Text(“Share”)
}
}
}
“`

Extending SwiftUI View

For a smoother experience, the share functionality can be abstracted into an extension on `View` protocol.

“`swift
extension View {
func shareSheet(items: [Any]) {
UIApplication.shared.windows.first?.rootViewController?.present(UIHostingController(rootView: ActivityViewController(items: items)), animated: true)
}
}

// Usage
Button(action: {
shareSheet(items: [“Share this text”])
}) {
Text(“Share”)
}
“`

With the introduction of ShareSheet in SwiftUI using UIViewControllerRepresentable and its usage refinement via extension, sharing data across apps became an easy task in SwiftUI, retaining the same simplicity and flexibility as in UIKit.

Related posts:

Leave a Comment