如何在Swift中将字符串编码为Base64?

时间:2015-03-31 09:27:45

标签: swift base64

我想将字符串转换为Base64。我在几个地方找到了答案,但它在Swift中不再起作用了。我正在使用Xcode 6.2。我相信答案可能适用于以前的Xcode版本,而不是Xcode 6.2。

有人可以指导我在Xcode 6.2中执行此操作吗?

我找到的答案是这个,但它在我的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)")

参考:http://iosdevelopertips.com/swift-code/base64-encode-decode-swift.html

14 个答案:

答案 0 :(得分:146)

<强>夫特

import UIKit

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

答案 1 :(得分:55)

我没有安装6.2,但我认为6.3在这方面没有任何不同:

dataUsingEncoding返回一个可选项,因此您需要打开它。

NSDataBase64EncodingOptions.fromRaw已替换为NSDataBase64EncodingOptions(rawValue:)。稍微令人惊讶的是,这不是一个可用的初始化程序,所以你不需要打开它。

但由于NSData(base64EncodedString:) 一个可用的初始化程序,您需要打开它。

顺便说一句,所有这些更改都是由Xcode迁移器建议的(点击排水沟中的错误消息,它有一个“修复它”建议)。

最终代码,为了避免强制解包而重写,看起来像这样:

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

(如果使用Swift 1.2,您可以使用多个if-lets而不是地图)

答案 2 :(得分:19)

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

答案 3 :(得分:12)

经过深入研究后我找到了解决方案

编码

.tmp.foo

解码

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

有关此http://creativecoefficient.net/swift/encoding-and-decoding-base64/

的更多信息

答案 4 :(得分:12)

Xcode 8.3.2•Swift 3.1

extension String {
    var data:          Data  { return Data(utf8) }
    var base64Encoded: Data  { return data.base64EncodedData() }
    var base64Decoded: Data? { return Data(base64Encoded: self) }
}

extension Data {
    var string: String? { return String(data: 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.string?.base64Decoded?.string ?? "") // iOS Developer Tips encoded in Base64

答案 5 :(得分:12)

Swift 4.2

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

答案 6 :(得分:5)

Swift 3或4

let base64Encoded = Data("original string".utf8).base64EncodedString()

答案 7 :(得分:5)

Swift 3

这是为Swift 3更新的简单String扩展,允许在解码时出现错误时保留选项。

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

示例:

let testString = "A test string."

let encoded = testString.toBase64() // "QSB0ZXN0IHN0cmluZy4="

guard let decoded = encoded.fromBase64() // "A test string."
    else { return } 

答案 8 :(得分:2)

经过一切努力,我确实喜欢这样。

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

在我调用另一个函数将解码后的字符串转换为字典

之后
        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
}

答案 9 :(得分:2)

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

答案 10 :(得分:0)

SwiftyBase64(完全披露:我写的)是一个原生的Swift Base64编码(没有解码库。有了它,你可以编码标准Base64:

let bytesToEncode : [UInt8] = [1,2,3]
let base64EncodedString = SwiftyBase64.EncodeString(bytesToEncode)

或URL和文件名安全Base64:

let bytesToEncode : [UInt8] = [1,2,3]
let base64EncodedString = SwiftyBase64.EncodeString(bytesToEncode, alphabet:.URLAndFilenameSafe)

答案 11 :(得分:0)

在Swift 2.0中的@Airspeed Velocity回答:

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

答案 12 :(得分:0)

Swift 4.2

var base64String = "my fancy string".data(using: .utf8, allowLossyConversion: false)?.base64EncodedString()

要解码,请参见(来自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)")
    }
}

答案 13 :(得分:0)

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
    }

}