I'm looking for a way to save a PDF file on my project directory, I've received a base 64 pdf string from a Web Service yet. Do I have to convert it to NSData or something like that?
I'm new at coding in Swift but I can follow your instructions.
I hope you can help me. Thanks
答案 0 :(得分:11)
是的,您必须将其转换为数据,然后将其保存到设备上的文档目录中。像这样的函数可以工作:
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)
}
答案 1 :(得分:0)
You want something like:
if let d = Data(base64Encoded: base64string) {
do {
try d.write(to: outputFile)
} catch {
// handle error
}
}
Where base64string
is the base64 PDF string, and outputFile
is a URL for the PDF output file.