Thanks for these answers, but I'm afraid I need a bit more help. How do you go about presenting the activityViewController? Could you show this in a small example app?
I had previously written this and it does share but it creates 2 files, and doesn't present any way to rename the file.
import SwiftUI
import UIKit
struct ContentView: View {
@State private var showShareSheet = false
@State private var textItem1 = ""
@State private var textItem2 = ""
// @State private var shareItems: [Any] = [
// "Check out this file!",
// URL(fileURLWithPath: FileManager.documentsDirectory.path()) // Replace with a real file URL
// ]
var shareItems: [Any] {
[ textItem1,
textItem2
// URL(fileURLWithPath: "TinySavedItems")
]
}
var body: some View {
VStack {
TextField("enter text", text: $textItem1)
.padding()
TextField("enter text", text: $textItem2)
.padding()
Button("Share", systemImage: "square.and.arrow.up") {
showShareSheet = true
}
.sheet(isPresented: $showShareSheet) {
ActivityViewController(activityItems: shareItems)
}
}
}
struct ActivityViewController: UIViewControllerRepresentable {
// Items to share (e.g., text, URLs, files)
let activityItems: [Any]
// Custom activities (optional)
let applicationActivities: [UIActivity]? = nil
// Completion handler (optional)
@Environment(\.dismiss) var dismiss
// Create the UIActivityViewController
func makeUIViewController(context: Context) -> UIActivityViewController {
let vc = UIActivityViewController(
activityItems: activityItems,
applicationActivities: applicationActivities
)
vc.excludedActivityTypes = [
.postToFacebook, .postToTwitter
]
// Handle completion (e.g., dismiss after sharing)
vc.completionWithItemsHandler = { _, success, _, error in
if success || error != nil {
dismiss() // Close the sheet after sharing
}
}
return vc
}
func updateUIViewController(_ uiViewController: UIActivityViewController, context: Context) {} //doesn't do anything but is required
}
}