How to convert a base64String to String in Swift?

swift base64 decode to byte array
convert base64 string to data swift
encode string swift
how to convert uiimage to string in swift
string decode
string to base64 encoded swift
swift base 64 encode string
password decode

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

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

Swift 3: Base64 encoding and decoding strings · GitHub, @stinger Can you please provide whole function to convert Base64 to Image & vice versa in Swift 3? Questions: I want to convert a string to a base64. I found same answer 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 not Xcode 6.2.


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

Extension for Encoding and Decoding Strings in Base64 in Swift, Here is an extension to base 64 encode and decode strings in Swift (3) extension String { func fromBase64() -> String? { guard let data  iOS Swift Convert Image to and from base64 String example Labels: Image, iOS, Swift. No comments: Post a Comment.


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)
}

base64EncodedString(options:), Creates a Base64 encoded string from the string using the given options. SDKs. iOS 7.0+; macOS 10.9+; Mac Catalyst 13.0+; tvOS 9.0+; watchOS 2.0+. Framework Options for methods used to Base64 encode data. struct NSData. Extends String class import Foundation extension String { func base64Encoded() -> String { let plainData = dataUsingEncoding(NSUTF8StringEncoding) let base64String = plainData?.base64EncodedStringWithOptions(NSDataBase64EncodingOptions.fromRaw(0)!) return base64String!


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)\"")
    }
}

Encoding and Decoding Base64, let decodedData = NSData (base64EncodedString: base64String, options: let decodedString = NSString (data: decodedData, encoding:  Swift iOS8 // prgm mark ---- // convert images into base64 and keep them into string func convertImageToBase64(image: UIImage) -> String { var imageData = UIImagePNGRepresentation(image) let base64String = imageData.base64EncodedStringWithOptions(.allZeros) return base64String }// end convertImageToBase64 // prgm mark ---- // convert images into base64 and keep them into string func


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 anOptional string: "Hello World!"

Source

Encoding and Decoding Base64 in Swift. Advanced String , Before I can encode existing image data into the Base64 string, I will need to have UIImge create. To create a new UIImage in Swift I can add an  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


UIImage Base64 Encoding and Decoding in Swift, let resultNSString = NSString(data: resultData as Data, encoding: String.​Encoding.utf8.rawValue)! //Convert NSString to String let resultString =  In this Swift tutorial, you will learn how to encode UIImage data to Base64 string. To verify that the UIImage data was correctly encoded into the Base64 string, we will decode the Base64 string back into image data and will create a new UIImage using this data.


Convert NSData/[UInt8] to Base64 in Swift, func base64Convert(base64String: String?) -> UIImage{ if (base64String?.​isEmpty)! { return #imageLiteral(resourceName: "no_image_found") }else { // !!! Convert Data To Base64 Swift - Online base64, base64 decode, base64 encode, base64 converter, python, to text _decode decode image, javascript, convert to image, to string java b64 decode, decode64 , file to, java encode, to ascii php, decode php , encode to file, js, _encode, string to text to decoder, url characters, atob javascript, html img, c# encode, 64 bit decoder, decode linuxbase


iOS Notes 25: How to convert Base64String to UIImage?[UPDATED , base64EncodedString() } func base64Decoded() -> String? { guard let data = Data(base64Encoded: self) else { return nil } return String(data:  As a developer, you will face converting base64String :) I know, it looks like scary at first but you just need some separation or just use it with my function :) At this function, it checks your…