3

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 ?

2 Answers 2

6

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.

Sign up to request clarification or add additional context in comments.

Comments

0

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)")
    }
}

1 Comment

Yes, thanks to point that out. I am deleting the temp file in the viewcontrollers deinit, but did not mention it.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.