How to convert a base64String to String in Swift?

后端 未结 5 1862
一个人的身影
一个人的身影 2020-12-03 03:03

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

    //Code
    var jsonResult = NSJSON         


        
相关标签:
5条回答
  • 2020-12-03 03:26

    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

    0 讨论(0)
  • 2020-12-03 03:30

    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
    
    0 讨论(0)
  • 2020-12-03 03:32

    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)\"")
        }
    }
    
    0 讨论(0)
  • 2020-12-03 03:33

    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)
    }
    
    0 讨论(0)
  • 2020-12-03 03:38

    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

    0 讨论(0)
提交回复
热议问题