Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert a base64String to String in Swift?

Tags:

swift

base64

I am receiving a base64String from webservice response in NSData, how to convert that base64String to String in swift?

    //Code     var jsonResult = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers, error: &err) as! NSDictionary  // Response JSON from webservice     var base64String : String = ""     base64String = jsonResult["Base64String"] as! String  // Retrieve base64String as string from json response     println("Base64String Alone: \(base64String)")  // Code to decode that base64String let decodedData = NSData(base64EncodedString: base64String, options: NSDataBase64DecodingOptions(rawValue: 0))                                     println("Decoded:  \(decodedData)")                                     let decodedString = NSString(data: decodedData!, encoding: NSUTF8StringEncoding)                                     println(decodedString) // Prints nil 

Encode and decode of base64String works well for the files containing only text, if a file contains some table formats/images both encoding and decoding gives an invalid base64String. How to convert a file into base64String encode and decode whatever the contents of file ? File formats are doc, docx, pdf, txt

Advance thanks for any help !

like image 475
Sakthimuthiah Avatar asked Aug 06 '15 14:08

Sakthimuthiah


People also ask

What is Base64 encoded data?

Base64 is a group of similar binary-to-text encoding schemes that represent binary data in an ASCII string format by translating it into a radix-64 representation. The term Base64 originates from a specific MIME content transfer encoding.

How does Base64 look like?

Base-64 maps 3 bytes (8 x 3 = 24 bits) in 4 characters that span 6-bits (6 x 4 = 24 bits). The result looks something like "TWFuIGlzIGRpc3Rpb...".


2 Answers

try this

let base64Encoded = "YW55IGNhcm5hbCBwbGVhc3VyZS4="  let decodedData = Data(base64Encoded: base64Encoded)! let decodedString = String(data: decodedData, encoding: .utf8)!  print(decodedString)  println(decodedString) 

make sure your base 64 encoded string is valid

like image 191
nRewik Avatar answered Oct 12 '22 14:10

nRewik


Swift extension is handy.

extension String {     func base64Encoded() -> String? {         return data(using: .utf8)?.base64EncodedString()     }      func base64Decoded() -> String? {         guard let data = Data(base64Encoded: self) else { return nil }         return String(data: data, encoding: .utf8)     } }  "heroes".base64Encoded() // It will return: aGVyb2Vz "aGVyb2Vz".base64Decoded() // It will return: heroes 
like image 37
Ashok Avatar answered Oct 12 '22 14:10

Ashok