如何使用base64字符串制作PDF文件?迅速

Eli*_*dez 4 pdf base64 ios swift swift2

我正在寻找一种在我的项目目录中保存PDF文件的方法,我从Web服务中收到了一个基本的64 pdf字符串.我是否必须将其转换为NSData或类似的东西?

我是Swift编码的新手,但我可以按照你的指示操作.

我希望你能帮助我.谢谢

BJH*_*ios 13

是的,您必须将其转换为数据,然后将其保存到设备上的文档目录中.像这样的函数可以工作:

func saveBase64StringToPDF(_ base64String: String) {

    guard
        var documentsURL = (FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)).last,
        let convertedData = Data(base64Encoded: base64String)
        else {
        //handle error when getting documents URL
        return
    }

    //name your file however you prefer
    documentsURL.appendPathComponent("yourFileName.pdf")

    do {
        try convertedData.write(to: documentsURL)
    } catch {
        //handle write error here
    }

    //if you want to get a quick output of where your 
    //file was saved from the simulator on your machine
    //just print the documentsURL and go there in Finder
    print(documentsURL)
}
Run Code Online (Sandbox Code Playgroud)

  • 我们如何从应用程序中打开 pdf? (2认同)

Jim*_*ews 0

你想要这样的东西:

if let d = Data(base64Encoded: base64string) {
    do {
        try d.write(to: outputFile)
    } catch {
        // handle error
    }
}
Run Code Online (Sandbox Code Playgroud)

其中base64string是 base64 PDF 字符串,outputFile是 PDF 输出文件的 URL。