Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I make a PDF file using base64 string ? Swift [duplicate]

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

like image 882
Elizabeth Hernandez Avatar asked Oct 20 '16 19:10

Elizabeth Hernandez


1 Answers

Yes, you have to convert it to Data and then save it to the documents directory on the device. A function like this would work:

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)
}
like image 117
JAB Avatar answered Sep 20 '22 08:09

JAB