25 Feb 2018

Convert pdf & images to base64 string swift 4

Convert pdf & images to base64 string swift 4

Introduction to convert PDF and images to base64 string

While developing iOS apps and if there is a need of uploading image, documents like PDF, excel doc, word doc to server(central database for our app) either we prefer byte data to be uploaded or API requires to upload documents(images, PDF,  excel, word documents) in base64 string. So we need to convert our image or PDF etc. to base64 first and then request API to upload it to server. In this tutorial, we will learn how to encode image or PDF ( or and kind of document) data to base64 string and also decode base64 string to files as per their mime types(defines type of document).  You can get more info about base64 string from https://en.wikipedia.org/wiki/Base64

Below are the code snippets for converting image to base64 string in swift and other documents like pdf etc. and vice versa.

Encoding UIImage to base64 string in swift 4 : 


In the above code, we have a function named "convertImageTobase64", which is accepting two parameters

1. format -  in which we want to get binary data for our image (i.e. png or jpeg)
2. image - UIImage, we want to convert to base64

In the "viewDidLoad" function, we user the "convertImageTobase64" function and get base64 string representation of UIImage in swift 4.

Decoding base64 string into UIImage in swift 4:


In above code snippets, we have a function that is converting base64 string to UIImage. To use it you have to to pass base64 string and it will return you UIImage object.

You can use similar function of data object to convert any other document(PDF, excel etc.) to base64 string, only you need to convert respective document to Data object.

Where to go from here

In this tutorial, we learned how to convert UIImage to base64 string in swift 4 and also convert base64 string to UIImage object using "base64EncodedString" function Data class in swift 4. You can download the source from Base64EncodingDecodingswift4.zip

No comments:

Post a Comment