Reputation: 65
I have a SwiftUI app where I'm trying to share a PDF file using a ShareSheet. The PDF is generated and saved with a specified name, but when I try to share it using the ShareSheet, it sends with a default name. Can someone help me understand why this is happening and how to make it send with the specified name?
Here is my code for the ShareSheet and the PDF generation and sharing:
// MARK: SHARE SHEET ITSELF
struct ShareSheet: UIViewControllerRepresentable {
let activityItems: [Any]
let applicationActivities: [UIActivity]?
func makeUIViewController(context: Context) -> UIActivityViewController {
let activityViewController = UIActivityViewController(
activityItems: activityItems,
applicationActivities: applicationActivities
)
return activityViewController
}
func updateUIViewController(_ uiViewController: UIActivityViewController, context: Context) {
// Nothing to update here
}
}
// MARK: SAVING PDF
func saveScannedImagesAsPDF() {
// Check if there are scanned images to save
let fileNameTrimmed = fileName.trimmingCharacters(in: .whitespacesAndNewlines)
guard !fileNameTrimmed.isEmpty else {
print("File name cannot be empty.")
return
}
guard !scannedImages.isEmpty else {
print("No scanned images to save.")
return
}
// Get the documents directory URL
if let documentsDirectory = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first {
// Create a PDF document
let pdfDocument = PDFDocument()
// Iterate through the scanned images and add them to the PDF
for image in scannedImages {
if let pdfPage = PDFPage(image: image) {
pdfDocument.insert(pdfPage, at: pdfDocument.pageCount)
}
}
let pdfFileName = "\(fileName).pdf"
// Create the PDF file URL
let pdfFileURL = documentsDirectory.appendingPathComponent(pdfFileName)
// Save the PDF to the specified URL
pdfDocument.write(to: pdfFileURL)
// Optionally, you can save the URL to the array of signatureImageURLs
// signatureImageURLs.append(pdfFileURL)
// Print the URL of the saved PDF
print("Saved PDF at: \(pdfFileURL)")
fileSaved.toggle()
} else {
print("Unable to access the document directory.")
}
}
// MARK: CALLING SHEET
.sheet(isPresented: $isShareSheetPresented, onDismiss: {
// Optional: Code to run after the share sheet is dismissed
}) {
if let pdfData = sendingFile {
ShareSheet(activityItems: [pdfData], applicationActivities: nil)
}
}
// MARK: - APPENDING FILE
private func sendFile(fileURL: URL) {
if let pdfData = try? Data(contentsOf: fileURL) {
self.sendingFile = pdfData
print(sendingFile)
self.isShareSheetPresented = true
}
}
Upvotes: 0
Views: 229
Reputation: 65
You can use this instead of sendFile function, it will call a right ViewController for that.
private func share(fileURL: URL) {
let activityVC = UIActivityViewController(activityItems: [fileURL], applicationActivities: nil)
UIApplication.shared.windows.first?.rootViewController?.present(activityVC, animated: true, completion: nil)
}
Upvotes: 1