Search code examples
pdfswiftuipdfkit

SwiftUI save PDF to files from remote using PDFKit


I've tried to save PDF file from link with ActivityViewController by clicking Save File using PDFKit. But I found problem that my file for some reason comes as filename.txt

Below provided documentsView, which shows document's list. By clicking SAVE, starts saveAction, which contains documentName and URL

private var documentsView: some View{
        Group{
            Section(header: CustomHeaderView(title: sectionTitle)) {
                ForEach(viewModel.documents, id: \.self){ document in
                    VStack(spacing: 7){
                        DocumentRow(title: document.title ?? "", action: { saveAction(for: document) })
                    }
                }
                .sheet(isPresented: $isSavePresented){
                    ActivityViewController(activityItems: ["MyFileName" , pdfDocument])
                }
            }
        }
    }

private func saveAction(for document: PolicyDocument){
    guard let url = document.uRL else { return }
    guard let urlObject = URL(string: url) else { return }
    if let doc =  PDFDocument(url: urlObject){
        pdfDocument = doc
        isSavePresented.toggle()
    }
}

struct ActivityViewController: UIViewControllerRepresentable {
var activityItems: [Any]
var applicationActivities: [UIActivity]? = nil

func makeUIViewController(context: UIViewControllerRepresentableContext<ActivityViewController>) -> UIActivityViewController {
    let controller = UIActivityViewController(activityItems: activityItems, applicationActivities: applicationActivities)
    return controller
}

func updateUIViewController(_ uiViewController: UIActivityViewController, context: UIViewControllerRepresentableContext<ActivityViewController>) {}

}

SOLVED

by adding .dataRepresentation()! to pdfDocument


Solution

  • solved by adding .dataRepresentation() to file itself. Did with guard, just posting example below...

    Example:

    .sheet(isPresented: $isSavePresented){
          ActivityViewController(activityItems: ["MyFileName" , pdfDocument.dataRepresentation()!])
    }