Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Base64 Encoding/Decoding with Swift 2

My code was working well on Xcode 6.4 with Swift 1.2:

 var imageData = UIImageJPEGRepresentation(firstImageView.image!, 0.2)

 let base64String = imageData!.base64EncodedStringWithOptions(.allZeros)

Once I moved to Xcode 7 and Swift 2 the following error appeared:

type of expression is ambiguous without more context

So I tried:

let base64String = imageData!.base64EncodedStringWithOptions(options: NSDataBase64EncodingOptions.allZeros)

But there is no "allZeros" option among NSDataBase64EncodingOptions.

like image 467
Alaa Avatar asked Oct 06 '15 10:10

Alaa


People also ask

How do I decode a Base64 encoded string in Swift?

Try this: let base64Encoded = "YW55IGNhcm5hbCBwbGVhc3VyZS4=" var decodedString = "" if let decodedData = Data(base64Encoded: base64Encoded) { decodedString = String(data: decodedData, encoding: . utf8)! }

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...".

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.


1 Answers

You should use .Encoding64CharacterLineLength instead of .allZeros:

let imageData = UIImageJPEGRepresentation(firstImageView.image!, 0.2)

let base64String = imageData!.base64EncodedStringWithOptions(NSDataBase64EncodingOptions.Encoding64CharacterLineLength)
like image 181
Eric Aya Avatar answered Oct 12 '22 07:10

Eric Aya