Michael Konz
Michael Konz

Reputation: 543

How to specify a filename when saving pdf document to iOS Files App?

Using the PDFKit I have created a pdf document within my app. I can successfully show it in a preview and from the preview controller I use the following code to present the user the share actions:

@objc func shareAction(_ sender: UIBarButtonItem)
{
    if let data = documentData
    {
        let vc = UIActivityViewController(activityItems: [data], applicationActivities: [])
        present(vc, animated: true, completion: nil     
    }
}

documentData contains the created pdf document.

When the user selects "Save to Files" the document gets the default name "PDF Document.pdf", which the user can change.

How can I provide a different default filename ?

Upvotes: 3

Views: 1840

Answers (2)

Vincent Gigandet
Vincent Gigandet

Reputation: 948

Just an additional help.

You'd better delete the PDF files in tmp dir at appropriate time.

I call this func when viewController dismisses.

FYI

func deleteAllPDFs() {
    let predicate = NSPredicate(format: "self ENDSWITH '.pdf'")
    let defaultFileManager = FileManager.default

    do {
        let tmpDirURL = defaultFileManager.temporaryDirectory
        let contents = try defaultFileManager.contentsOfDirectory(atPath: tmpDirURL.path)
        let pdfs = contents.filter { predicate.evaluate(with: $0) }
        try pdfs.forEach { file in
            let fileUrl = tmpDirURL.appendingPathComponent(file)
            try defaultFileManager.removeItem(at: fileUrl)
        }
    }
    catch {
        print ("Failed to delete PDF with error: \(error)")
    }
}

Upvotes: 0

Michael Konz
Michael Konz

Reputation: 543

Not a real answer but rather a workaround that I figured out:

Rather than using the in-memory-copy data of the PDF, I can write it to the apps tmp folder:

var fileURL : URL?
do
{
    let filename = "myfilename.pdf"
    let tmpDirectory = FileManager.default.temporaryDirectory
    fileURL = tmpDirectory.appendingPathComponent(filename)
    try data.write(to: fileURL!)
}
catch
{
    print ("Cannot write PDF: \(error)")
}

The share action would then look like:

@objc func shareAction(_ sender: UIBarButtonItem)
{
    if let url = fileURL
    {
        let vc = UIActivityViewController(activityItems: [url], applicationActivities: [])
        present(vc, animated: true, completion: nil     
    }
}

Now the user gets "myfilename.pdf" shown as default filename when he chooses the "Save to Files" action.

Upvotes: 6

Related Questions