如何在Swift中将base64String转换为String?

时间:2015-08-06 14:59:35

标签: swift base64

我从NSData的webservice响应中接收到base64String,如何在swift中将base64String转换为String?

    //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

base64String的编码和解码适用于仅包含文本的文件,如果文件包含某些表格格式/图像,则编码和解码都会产生无效的base64String。如何将文件转换为base64String编码和解码文件的内容? 文件格式为doc,docx,pdf,txt

感谢任何帮助!

5 个答案:

答案 0 :(得分:29)

试试这个

3

确保您的base 64编码字符串有效

答案 1 :(得分:13)

Swift扩展很方便。

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

答案 2 :(得分:4)

我已经更新了Ashok Kumar S的答案,以在字符串大小不能被4整除时添加填充符,引发异常并返回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)
}

答案 3 :(得分:1)

以上答案是核心,但我有类似的错误

fatal error, found nil while unwrapping an optional value

解决方案是添加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
    }
}

并安全使用

var str = "HelloWorld"
if let base64Str = str.base64Encoded() {
    print("Base64 encoded string: \"\(base64Str)\"")
    if let trs = base64Str.base64Decoded() {
        print("Base64 decoded string: \"\(trs)\"")
    }
}

答案 4 :(得分:0)

您可以使用此扩展名对base64字符串进行加密/解密:

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

要编码:

"Hello World!".base64Encoded

结果是一个可选字符串:“ SGVsbG8gV29ybGQh”

要解码:

"SGVsbG8gV29ybGQh".base64Decoded

结果是一个可选字符串:“ Hello World!”

Source