How can I encode a string to Base64 in Swift? - swift

I want to convert a string to Base64. I found answers in several places, but it does not work anymore in Swift. I am using Xcode 6.2. I believe the answer might be work in previous Xcode versions and not Xcode 6.2.
Could someone please guide me to do this in Xcode 6.2?
The answer I found was this, but it does not work in my version of Xcode:
var str = "iOS Developer Tips encoded in Base64"
println("Original: \(str)")
// UTF 8 str from original
// NSData! type returned (optional)
let utf8str = str.dataUsingEncoding(NSUTF8StringEncoding)
// Base64 encode UTF 8 string
// fromRaw(0) is equivalent to objc 'base64EncodedStringWithOptions:0'
// Notice the unwrapping given the NSData! optional
// NSString! returned (optional)
let base64Encoded = utf8str.base64EncodedStringWithOptions(NSDataBase64EncodingOptions.fromRaw(0)!)
println("Encoded: \(base64Encoded)")
// Base64 Decode (go back the other way)
// Notice the unwrapping given the NSString! optional
// NSData returned
let data = NSData(base64EncodedString: base64Encoded, options: NSDataBase64DecodingOptions.fromRaw(0)!)
// Convert back to a string
let base64Decoded = NSString(data: data, encoding: NSUTF8StringEncoding)
println("Decoded: \(base64Decoded)")
ref: http://iosdevelopertips.com/swift-code/base64-encode-decode-swift.html

Swift
import Foundation
extension String {
func fromBase64() -> String? {
guard let data = Data(base64Encoded: self) else {
return nil
}
return String(data: data, encoding: .utf8)
}
func toBase64() -> String {
return Data(self.utf8).base64EncodedString()
}
}

I don’t have 6.2 installed but I don’t think 6.3 is any different in this regard:
dataUsingEncoding returns an optional, so you need to unwrap that.
NSDataBase64EncodingOptions.fromRaw has been replaced with NSDataBase64EncodingOptions(rawValue:). Slightly surprisingly, this is not a failable initializer so you don’t need to unwrap it.
But since NSData(base64EncodedString:) is a failable initializer, you need to unwrap that.
Btw, all these changes were suggested by Xcode migrator (click the error message in the gutter and it has a “fix-it” suggestion).
Final code, rewritten to avoid force-unwraps, looks like this:
import Foundation
let str = "iOS Developer Tips encoded in Base64"
println("Original: \(str)")
let utf8str = str.dataUsingEncoding(NSUTF8StringEncoding)
if let base64Encoded = utf8str?.base64EncodedStringWithOptions(NSDataBase64EncodingOptions(rawValue: 0))
{
println("Encoded: \(base64Encoded)")
if let base64Decoded = NSData(base64EncodedString: base64Encoded, options: NSDataBase64DecodingOptions(rawValue: 0))
.map({ NSString(data: $0, encoding: NSUTF8StringEncoding) })
{
// Convert back to a string
println("Decoded: \(base64Decoded)")
}
}
(if using Swift 1.2 you could use multiple if-lets instead of the map)
Swift 5 Update:
import Foundation
let str = "iOS Developer Tips encoded in Base64"
print("Original: \(str)")
let utf8str = str.data(using: .utf8)
if let base64Encoded = utf8str?.base64EncodedString(options: Data.Base64EncodingOptions(rawValue: 0)) {
print("Encoded: \(base64Encoded)")
if let base64Decoded = Data(base64Encoded: base64Encoded, options: Data.Base64DecodingOptions(rawValue: 0))
.map({ String(data: $0, encoding: .utf8) }) {
// Convert back to a string
print("Decoded: \(base64Decoded ?? "")")
}
}

Swift 4.2
"abcd1234".data(using: .utf8)?.base64EncodedString()

Xcode 11.4 • Swift 5.2 or later
extension StringProtocol {
var data: Data { Data(utf8) }
var base64Encoded: Data { data.base64EncodedData() }
var base64Decoded: Data? { Data(base64Encoded: string) }
}
extension LosslessStringConvertible {
var string: String { .init(self) }
}
extension Sequence where Element == UInt8 {
var data: Data { .init(self) }
var base64Decoded: Data? { Data(base64Encoded: data) }
var string: String? { String(bytes: self, encoding: .utf8) }
}
let original = "iOS Developer Tips encoded in Base64"
let utf8Data = original.data // 36 bytes
let base64EncodedString = utf8Data.base64EncodedString() // aU9TIERldmVsb3BlciBUaXBzIGVuY29kZWQgaW4gQmFzZTY0\n"
let base64EncodedData = utf8Data.base64EncodedData() // 48 bytes"
print("base64EncodedData:", original.base64Encoded) // 48 bytes
print("base64EncodedString:", original.base64Encoded.string ?? "") // "aU9TIERldmVsb3BlciBUaXBzIGVuY29kZWQgaW4gQmFzZTY0"
print("base64DecodedData:", original.base64Encoded.string?.base64Decoded ?? "") // 36 bytes
print("base64DecodedString:", original.base64Encoded.base64Decoded?.string ?? "") // iOS Developer Tips encoded in Base64

You could just do a simple extension like:
import UIKit
// MARK: - Mixed string utils and helpers
extension String {
/**
Encode a String to Base64
:returns:
*/
func toBase64()->String{
let data = self.dataUsingEncoding(NSUTF8StringEncoding)
return data!.base64EncodedStringWithOptions(NSDataBase64EncodingOptions(rawValue: 0))
}
}
iOS 7 and up

Swift 4.0.3
import UIKit
extension String {
func fromBase64() -> String? {
guard let data = Data(base64Encoded: self, options: Data.Base64DecodingOptions(rawValue: 0)) else {
return nil
}
return String(data: data as Data, encoding: String.Encoding.utf8)
}
func toBase64() -> String? {
guard let data = self.data(using: String.Encoding.utf8) else {
return nil
}
return data.base64EncodedString(options: Data.Base64EncodingOptions(rawValue: 0))
}
}

After thorough research I found the solution
Encoding
let plainData = (plainString as NSString).dataUsingEncoding(NSUTF8StringEncoding)
let base64String =plainData.base64EncodedStringWithOptions(NSDataBase64EncodingOptions.fromRaw(0)!)
println(base64String) // bXkgcGxhbmkgdGV4dA==
Decoding
let decodedData = NSData(base64EncodedString: base64String, options:NSDataBase64DecodingOptions.fromRaw(0)!)
let decodedString = NSString(data: decodedData, encoding: NSUTF8StringEncoding)
println(decodedString) // my plain data
More on this http://creativecoefficient.net/swift/encoding-and-decoding-base64/

Swift 5.1, Xcode 11:
public extension String {
/// Assuming the current string is base64 encoded, this property returns a String
/// initialized by converting the current string into Unicode characters, encoded to
/// utf8. If the current string is not base64 encoded, nil is returned instead.
var base64Decoded: String? {
guard let base64 = Data(base64Encoded: self) else { return nil }
let utf8 = String(data: base64, encoding: .utf8)
return utf8
}
/// Returns a base64 representation of the current string, or nil if the
/// operation fails.
var base64Encoded: String? {
let utf8 = self.data(using: .utf8)
let base64 = utf8?.base64EncodedString()
return base64
}
}

Swift 3 or 4
let base64Encoded = Data("original string".utf8).base64EncodedString()

Swift 3 / 4 / 5.1
Here is a simple String extension, allowing for preserving optionals in the event of an error when decoding.
extension String {
/// Encode a String to Base64
func toBase64() -> String {
return Data(self.utf8).base64EncodedString()
}
/// Decode a String from Base64. Returns nil if unsuccessful.
func fromBase64() -> String? {
guard let data = Data(base64Encoded: self) else { return nil }
return String(data: data, encoding: .utf8)
}
}
Example:
let testString = "A test string."
let encoded = testString.toBase64() // "QSB0ZXN0IHN0cmluZy4="
guard let decoded = encoded.fromBase64() // "A test string."
else { return }

After all struggle I did like this.
func conversion(str:NSString)
{
if let decodedData = NSData(base64EncodedString: str as String, options:NSDataBase64DecodingOptions(rawValue: 0)),
let decodedString = NSString(data: decodedData, encoding: NSUTF8StringEncoding) {
print(decodedString)//Here we are getting decoded string
After I am calling another function for converting decoded string to dictionary
self .convertStringToDictionary(decodedString as String)
}
}//function close
//for string to dictionary
func convertStringToDictionary(text: String) -> [String:AnyObject]? {
if let data = text.dataUsingEncoding(NSUTF8StringEncoding) {
do {
let json = try NSJSONSerialization.JSONObjectWithData(data, options: []) as? [String:AnyObject]
print(json)
if let stack = json!["cid"] //getting key value here
{
customerID = stack as! String
print(customerID)
}
} catch let error as NSError {
print(error)
}
}
return nil
}

FOR SWIFT 3.0
let str = "iOS Developer Tips encoded in Base64"
print("Original: \(str)")
let utf8str = str.data(using: String.Encoding.utf8)
if let base64Encoded = utf8str?.base64EncodedString(options: NSData.Base64EncodingOptions(rawValue: 0))
{
print("Encoded: \(base64Encoded)")
if let base64Decoded = NSData(base64Encoded: base64Encoded, options: NSData.Base64DecodingOptions(rawValue: 0))
.map({ NSString(data: $0 as Data, encoding: String.Encoding.utf8.rawValue) })
{
// Convert back to a string
print("Decoded: \(base64Decoded)!")
}
}

Swift 4.2
var base64String = "my fancy string".data(using: .utf8, allowLossyConversion: false)?.base64EncodedString()
to decode, see (from https://gist.github.com/stinger/a8a0381a57b4ac530dd029458273f31a)
//: # Swift 3: Base64 encoding and decoding
import Foundation
extension String {
//: ### Base64 encoding a string
func base64Encoded() -> String? {
if let data = self.data(using: .utf8) {
return data.base64EncodedString()
}
return nil
}
//: ### Base64 decoding a string
func base64Decoded() -> String? {
if let data = Data(base64Encoded: self) {
return String(data: data, encoding: .utf8)
}
return nil
}
}
var str = "Hello, playground"
print("Original string: \"\(str)\"")
if let base64Str = str.base64Encoded() {
print("Base64 encoded string: \"\(base64Str)\"")
if let trs = base64Str.base64Decoded() {
print("Base64 decoded string: \"\(trs)\"")
print("Check if base64 decoded string equals the original string: \(str == trs)")
}
}

public extension String{
///base64EncodedString
var base64EncodedString:String{
if let data = data(using: .utf8){
return data.base64EncodedString()
}
return ""
}
}

SwiftyBase64 (full disclosure: I wrote it) is a native Swift Base64 encoding (no decoding library. With it, you can encode standard Base64:
let bytesToEncode : [UInt8] = [1,2,3]
let base64EncodedString = SwiftyBase64.EncodeString(bytesToEncode)
or URL and Filename Safe Base64:
let bytesToEncode : [UInt8] = [1,2,3]
let base64EncodedString = SwiftyBase64.EncodeString(bytesToEncode, alphabet:.URLAndFilenameSafe)

#Airspeed Velocity answer in Swift 2.0:
let str = "iOS Developer Tips encoded in Base64"
print("Original: \(str)")
let base64Encoded = str.dataUsingEncoding(NSUTF8StringEncoding)!.base64EncodedStringWithOptions([])
print("Encoded: \(base64Encoded)")
let base64DecodedData = NSData(base64EncodedString: base64Encoded, options: [])!
var base64DecodedString = String(data: base64DecodedData, encoding: NSUTF8StringEncoding)!
print("Decoded: \(base64DecodedString)")

A short example of converting Data to String:
import Foundation
let base64EncodedString = "SGVsbG8sIFdvcmxkIQ=="
if let data = Data(base64Encoded: base64EncodedString) {
if let str = String(data: data, encoding: .utf8) {
print(str) // Output: "Hello, World!"
}
}
This code first creates a Data object from the base64-encoded string using the Data(base64Encoded:) initializer. Then it creates a string from the data object using the String(data:encoding:) initializer.
Note that the Data(base64Encoded:) and String(data:encoding:) initializers can both throw errors, so it's a good idea to wrap the code in a do-catch block to handle any potential errors.

Related

Swift 4: Type of expression is ambiguous without more context inside loop

I have a question:
I'm retrieving a long string made of some base 64 strings attached together with ";" separating each of them inside said string.
Here's my code:
if(item.photo != "null"){
let b64fullstring = item.photo
if(b64fullstring!.contains(";")){
let photos = b64fullstring!.split(separator: ";")
for pic in photos{
let base64encodedstring = pic
let decodedData = Data(base64Encoded: base64encodedstring!, options: Data.Base64DecodingOptions.ignoreUnknownCharacters)!
let decodedString = String(data: decodedData, encoding: .utf8)!
print(pic)
}
}
}
Its gives me the following error on the "data" function;
Type of expression is ambiguous without more context
I really don't get it.
When working on a single string, it works perfectly fine. But when using a loop, it gives this message for some reason.
Thank you for taking some of your time for helping me.
Swift errors are not very helpful. The problem there is that split method returns an array of substrings:
func split(separator: Character, maxSplits: Int = Int.max, omittingEmptySubsequences: Bool = true) -> [Substring]
And the Data initializer expects a String:
init?(base64Encoded base64String: String, options: Data.Base64DecodingOptions = [])
You just need to initialize a new string from your substring:
if let photos = b64fullstring?.split(separator: ";") {
for pic in photos {
if let decodedData = Data(base64Encoded: String(pic), options: .ignoreUnknownCharacters) {
if let decodedString = String(data: decodedData, encoding: .utf8) {
print(pic)
}
}
}
}
Another option is to use components(separatedBy:) method which returns an array of strings instead of substrings:
func components<T>(separatedBy separator: T) -> [String] where T : StringProtocol
if let photos = b64fullstring?.components(separatedBy: ";") {
for pic in photos {
if let decodedData = Data(base64Encoded: pic, options: .ignoreUnknownCharacters) {
if let decodedString = String(data: decodedData, encoding: .utf8) {
print(pic)
}
}
}
}

How can I convert a string, such as "iso-8859-1", to it's String.Encoding counterpart?

After sending a HTTP request from Swift, I get a field in the response called textEncodingName.
I want to convert the data object I also received into a string containing its contents, and to do this, I'm using String(data: data!, encoding: .utf8). This works most of the time, because most websites are UTF-8 encoded. But with, for example, https://www.google.co.uk, the response.textEncodingName == "iso-8859-1".
I guess other websites would use even more obscure encodings, so my question is this: how can I find the right encoding to convert my data object to the correct string.
You can simply try String.Encoding.windowsCP1250 for iso-8859-1. Please refer https://en.wikipedia.org/wiki/Windows-1250
String(data: data, encoding: .windowsCP1250)
OR..
I found a few steps that will take you from the textEncodingName to the corresponding String.Encoding value:
let estr = "iso-8859-1"
let cfe = CFStringConvertIANACharSetNameToEncoding(estr as CFString)
let se = CFStringConvertEncodingToNSStringEncoding(cfe)
let encoding = String.Encoding(rawValue: se)
This is largely based on the documentation for URLResponse.textEncodingName:
You can convert this string to a CFStringEncoding value by calling CFStringConvertIANACharSetNameToEncoding(:). You can subsequently convert that value to an NSStringEncoding value by calling CFStringConvertEncodingToNSStringEncoding(:).
Here's an update that checks to see if the original text encoding string is valid or not:
let estr = "XXX"
let cfe = CFStringConvertIANACharSetNameToEncoding(estr as CFString)
if cfe != kCFStringEncodingInvalidId {
let se = CFStringConvertEncodingToNSStringEncoding(cfe)
let sse = String.Encoding(rawValue: se)
print("sse = \(sse)")
} else {
print("Invalid")
}
I would write an enum with a String raw value and a computed property to return the appropriate String.Encoding value. Then you can use its init(rawValue:) to create an instance.
import Foundation
enum APITextEncoding : String
{
case iso8859_1 = "iso-8859-1"
// etc.
var encoding: String.Encoding
{
switch self
{
case .iso8859_1:
return .isoLatin1
// etc.
}
}
}
let receivedEncoding = APITextEncoding(rawValue: encodingDescription)
let receivedText = String(data: receivedData, encoding: receivedEncoding.encoding)
In Swift You can use:
guard let string = String(data: data, encoding: .isoLatin1) else {return}
guard let perfectData = string.data(using: .utf8, allowLossyConversion: true) else {return}
In swift you can use:
func getTextFrom(_ url: URL) -> String? {
guard let data = try? Data(contentsOf: url) else {
return nil
}
return String(data: data, encoding: .utf8) ??
String(data: data, encoding: .isoLatin1)
}

Swift Encode/decode emojis

I'm trying to encode and decode Emojis to send them to my database.
I use this to encode:
var comentario = String()
let data = Comment.data(using: String.Encoding.nonLossyASCII, allowLossyConversion: true)
if let data = data {
let emojiString = NSString(data: data, encoding: String.Encoding.utf8.rawValue)! as String
comentario = emojiString
}
And it works. But now I don't know how to decode the emoji.
This is the type of encode ---> \ud83d\ude1a
Your encoding code can be simplified to
func encode(_ s: String) -> String {
let data = s.data(using: .nonLossyASCII, allowLossyConversion: true)!
return String(data: data, encoding: .utf8)!
}
Note that it encodes all non-ASCII characters as \uNNNN, not only
Emojis. Decoding is done by reversing the transformations:
func decode(_ s: String) -> String? {
let data = s.data(using: .utf8)!
return String(data: data, encoding: .nonLossyASCII)
}
This returns an optional because it can fail for invalid input.
Example:
let s = "Hello 😃."
let e = encode(s)
print(e) // Hello \ud83d\ude03.
if let d = decode(e) {
print(d) // Hello 😃.
}
Of course you can also define the code as extension methods of the
String type, and you might want to choose better function names.
I fixed this. If you have a server with encode utf8mb4, then for encoding emojis use this code:
var comentario = String()
let data = Comment.data(using: String.Encoding.nonLossyASCII, allowLossyConversion: true)
if let data = data {
let emojiString = NSString(data: data, encoding: String.Encoding.utf8.rawValue)! as String
comentario = emojiString
}// comentario contains the emoji encoded
DECODING:
let data = comentarios.data(using: String.Encoding.utf8, allowLossyConversion: false)
if data != nil{
let valueunicode = NSString(data: data!, encoding: String.Encoding.nonLossyASCII.rawValue) as? String
if valueunicode != nil{
comentarios = valueunicode!
}
}//comentarios contantes the deecode string(emoji)

Decode base64 to binary file in swift

How can I decode base64 binary file to the file in swift?like docx
I used this code but return always nil.
if let decodedData = NSData(base64EncodedString:"base64string" , options:.Ig(rawValue: 0)),
let decodedString = NSString(data: decodedData, encoding: NSUTF8StringEncoding) {
print(decodedString)
}
You are supposed to pass a base 64-string into the NSData-initializer ("base64string" is not a valid base64, hence the initializer returns nil).
let stringToEncode = "testString"
let stringData = stringToEncode.dataUsingEncoding(NSUTF8StringEncoding)
let base64String = stringData!.base64EncodedStringWithOptions(NSDataBase64EncodingOptions(rawValue: 0))
if let decodedData = NSData(base64EncodedString:base64String , options: .IgnoreUnknownCharacters),
let decodedString = NSString(data: decodedData, encoding: NSUTF8StringEncoding) {
print(decodedString)
}
let myString = "my data"
Encoding
let plainData = (myString as NSString).dataUsingEncoding(NSUTF8StringEncoding)
let base64String = plainData.base64EncodedStringWithOptions(NSDataBase64EncodingOptions.fromRaw(0)!)
println(base64String)
Decoding
if let decodedData = NSData(base64EncodedString: base64String, options:NSDataBase64DecodingOptions.fromRaw(0)!) {
let decodedString = NSString(data: decodedData, encoding: NSUTF8StringEncoding)
println(decodedString)
}
In Swift 4, you can do base64 encoding or decoding like this:
extension Data {
init?(base64String: String) {
self.init(base64Encoded: base64String)
}
var base64String: String {
return self.base64EncodedString()
}
}
extension String {
init?(base64String: String) {
guard let data = Data(base64String: base64String) else {
return nil
}
self.init(data: data, encoding: .utf8)
}
var base64String: String {
return self.data(using: .utf8)!.base64String
}
}

How to convert a base64String to String in Swift?

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 !
Try this:
let base64Encoded = "YW55IGNhcm5hbCBwbGVhc3VyZS4="
var decodedString = ""
if let decodedData = Data(base64Encoded: base64Encoded) {
decodedString = String(data: decodedData, encoding: .utf8)!
}
if !decodedString.isEmpty {
print(decodedString)
} else {
print("Oops, invalid input format!")
}
Make sure your base 64 encoded string is valid.
WARNING (edit)
In most base64 decoding implementations like Java, the padding-character is not needed, but Data(base64Encoded:) returns nil if it's missing.
Swift 5 solution; use String.fromBase64(_:) instead, after implementing like:
extension Data {
/// Same as ``Data(base64Encoded:)``, but adds padding automatically
/// (if missing, instead of returning `nil`).
public static func fromBase64(_ encoded: String) -> Data? {
// Prefixes padding-character(s) (if needed).
var encoded = encoded;
let remainder = encoded.count % 4
if remainder > 0 {
encoded = encoded.padding(
toLength: encoded.count + 4 - remainder,
withPad: "=", startingAt: 0);
}
// Finally, decode.
return Data(base64Encoded: encoded);
}
}
extension String {
public static func fromBase64(_ encoded: String) -> String? {
if let data = Data.fromBase64(encoded) {
return String(data: data, encoding: .utf8)
}
return nil;
}
}
As mentioned on editor's profile,
above edit's code allows Apache 2.0 license as well,
without attribution need.
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
i've made an update to Ashok Kumar S answer to add filler character when string size is not divisible by 4, raising an exception and returning nil
extension String {
func base64Encoded() -> String? {
return data(using: .utf8)?.base64EncodedString()
}
func base64Decoded() -> String? {
var st = self;
if (self.count % 4 <= 2){
st += String(repeating: "=", count: (self.count % 4))
}
guard let data = Data(base64Encoded: st) else { return nil }
return String(data: data, encoding: .utf8)
}
You can encrypt/decrypt base64 strings using this extension:
public extension String {
var base64Decoded: String? {
guard let decodedData = Data(base64Encoded: self) else { return nil }
return String(data: decodedData, encoding: .utf8)
}
var base64Encoded: String? {
let plainData = data(using: .utf8)
return plainData?.base64EncodedString()
}
}
To Encode:
"Hello World!".base64Encoded
Result is an Optional string: "SGVsbG8gV29ybGQh"
To Decode:
"SGVsbG8gV29ybGQh".base64Decoded
Result is an Optional string: "Hello World!"
Source
The above answers are core, but i had an error like
fatal error, found nil while unwrapping an optional value
The solution is adding options
extension String {
//: ### Base64 encoding a string
func base64Encoded() -> String? {
if let data = self.data(using: .utf8) {
return data.base64EncodedString()
}
return nil
}
//: ### Base64 decoding a string
func base64Decoded() -> String? {
if let data = Data(base64Encoded: self, options: .ignoreUnknownCharacters) {
return String(data: data, encoding: .utf8)
}
return nil
}
}
and use it safely
var str = "HelloWorld"
if let base64Str = str.base64Encoded() {
print("Base64 encoded string: \"\(base64Str)\"")
if let trs = base64Str.base64Decoded() {
print("Base64 decoded string: \"\(trs)\"")
}
}