如何给pdfData一个文件名供用户保存swift

时间:2018-09-23 15:00:59

标签: swift pdf save filenames

我将pdfData提供给用户保存。他可以保存到文件并制作文件,但是pdf文件的默认名称是:PDF document.pdf。如果可以的话,我想要自己的文件名。也许我可以在将pdfData提供给UIActivityViewController之前更改pdfData中的文件名?

这是我的代码

    // Create page rect
    let pageRect = CGRect(x: 0, y: 0, width: 595.28, height: 841.89) // A4, 72 dpi

    // Create PDF context and draw
    let pdfData = NSMutableData()

    UIGraphicsBeginPDFContextToData(pdfData, pageRect, nil)
    UIGraphicsBeginPDFPage()

    // From here you can draw page, best make it in a function
    PdfErstellung.PdfErstellen(auswahlZeilen, vitalstoffWerteListe, heuteString)

    UIGraphicsEndPDFContext()

    // Save pdf DATA through user
    let activityViewController = UIActivityViewController(activityItems: [pdfData], applicationActivities: nil)
    activityViewController.popoverPresentationController?.sourceView = self.view // für IPAD nötig
    self.present(activityViewController, animated: true, completion: nil)

-更新-

我的新想法,首先尝试保存文件并尝试使用URL,如果失败,则直接使用pdfData,因为在某些模拟器中,使用URL不会出错,而在其他模拟器中则给出错误。

更多信息:https://stackoverflow.com/a/52499637/10392572

2 个答案:

答案 0 :(得分:2)

您只需要将pdfData保存到一个临时文件URL并共享该URL。

let temporaryFolder = FileManager.default.temporaryDirectory
let fileName = "document.pdf"
let temporaryFileURL = temporaryFolder.appendingPathComponent(fileName)
print(temporaryFileURL.path)  // /Users/lsd/Library/Developer/XCPGDevices/E2003834-07AB-4833-B206-843DC0A52967/data/Containers/Data/Application/322D1F1D-4C97-474C-9040-FE5E740D38CF/tmp/document.pdf
do {
    try pdfData.write(to: temporaryFileURL)
    // your code
    let activityViewController = UIActivityViewController(activityItems: [temporaryFileURL], applicationActivities: nil)
} catch {
    print(error)
}

答案 1 :(得分:0)

并非您还可以将AirDrop设置为如下使用用户标题:

    let temporaryFolder = FileManager.default.temporaryDirectory
    let fileName = "Carburant Discount Historique des Prix au \(Date()).json"
    let temporaryFileURL = temporaryFolder.appendingPathComponent(fileName)
    print(temporaryFileURL.path)
    do {
        try? FileManager.default.removeItem(at: temporaryFileURL)

        try json.write(to: temporaryFileURL)
    }
    catch let error {
        print("\(#function): *** Error while writing json to temporary file. \(error.localizedDescription)")
        alert("Export impossible")
        return
    }

    /// Sets the **title** along with the URL
    let dataToShare: [Any] = ["Historique des prix", temporaryFileURL]

    let activityViewController = UIActivityViewController(activityItems: dataToShare, applicationActivities: nil)