在swift中将base64解码为二进制文件

时间:2016-07-25 04:26:02

标签: swift binary base64 decode

如何将base64二进制文件解码为swift文件?比如docx 我使用了这段代码,但总是返回nil。

if let decodedData = NSData(base64EncodedString:"base64string" , options:.Ig(rawValue: 0)),
               let decodedString = NSString(data: decodedData, encoding: NSUTF8StringEncoding) {
               print(decodedString) 
           }

3 个答案:

答案 0 :(得分:0)

您应该将基本64字符串传递给NSData - 初始值设定项("base64string"不是有效的base64,因此初始化程序返回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)
}

答案 1 :(得分:0)

let myString = "my data"

<强>编码

let plainData = (myString as NSString).dataUsingEncoding(NSUTF8StringEncoding)
let base64String = plainData.base64EncodedStringWithOptions(NSDataBase64EncodingOptions.fromRaw(0)!)
println(base64String)

<强>解码

if let decodedData = NSData(base64EncodedString: base64String, options:NSDataBase64DecodingOptions.fromRaw(0)!) {
let decodedString = NSString(data: decodedData, encoding: NSUTF8StringEncoding)    
println(decodedString)
}

答案 2 :(得分:0)

在Swift 4中,您可以像这样执行base64编码或解码:

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
    }

}