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


115

我想将字符串转换为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


Swift扩展程序干净方便。stackoverflow.com/a/46969102/1996294
Ashok,

Answers:


69

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

dataUsingEncoding 返回一个可选的,所以您需要打开它。

NSDataBase64EncodingOptions.fromRaw已替换为NSDataBase64EncodingOptions(rawValue:)。令人惊讶的是,这不是一个失败的初始化器,因此您无需拆开包装。

但是,由于它NSData(base64EncodedString:) 一个失败的初始化器,因此您需要对其进行包装。

顺便说一句,所有这些更改都是Xcode迁移器建议的(单击装订线中的错误消息,它带有“ fix-it”建议)。

最终代码经过重写以避免强制展开,如下所示:

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-let代替地图)

Swift 5更新:

import Foundation

let str = "iOS Developer Tips encoded in Base64"
print("Original: \(str)")

let utf8str = str.data(using: .utf8)

if let base64Encoded = utf8str?.base64EncodedString(options: Data.Base64EncodingOptions(rawValue: 0)) {
    print("Encoded: \(base64Encoded)")

    if let base64Decoded = Data(base64Encoded: base64Encoded, options: Data.Base64DecodingOptions(rawValue: 0))
    .map({ String(data: $0, encoding: .utf8) }) {
        // Convert back to a string
        print("Decoded: \(base64Decoded ?? "")")
    }
}

3
您不能只是[]代替NSDataBase64EncodingOptions(rawValue: 0)吗?
硫磺

198

迅速

import Foundation

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

}

这是安全代码,您需要处理可选内容。
Mohammad Zaid Pathan

新增了Swift 3语法
Matthew Knippen '16

3
我尝试转换此基数为64的字符串:dfYcSGpvBqyzvkAXkdbHDA==预期的输出必须为:u�Hjo���@���但上面的函数返回nil。您可以在以下站点上检查上述base-64字符串的输出:Site1Site2
Chanchal Raj'Jan

@ZaidPathan,已修复!
Darkngs

22

您可以做一个简单的扩展,例如:

import UIKit

// MARK: - Mixed string utils and helpers
extension String {


    /**
    Encode a String to Base64

    :returns: 
    */
    func toBase64()->String{

        let data = self.dataUsingEncoding(NSUTF8StringEncoding)

        return data!.base64EncodedStringWithOptions(NSDataBase64EncodingOptions(rawValue: 0))

    }

}

iOS 7及更高版本


20

斯威夫特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))
    }
}

我使用相同的代码,但还是,编者给出了错误:类型的值“数据”在斯威夫特4.0.3没有成员“base64EncodedStringWithOptions”
阿什维尼Chougale

5
如果Data(self.utf8).base64EncodedString()没有可选参数,则toBase64()不需要。从下面的答案中:stackoverflow.com/a/35360697/129202
Jonny

19

斯威夫特4.2

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

13

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

编码方式

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

解码

    let decodedData = NSData(base64EncodedString: base64String, options:NSDataBase64DecodingOptions.fromRaw(0)!)
    let decodedString = NSString(data: decodedData, encoding: NSUTF8StringEncoding)    
    println(decodedString) // my plain data

有关此http://creativecoefficient.net/swift/encoding-and-decoding-base64/的更多信息


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

11

迅捷3或4

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

1
页面上的最佳答案,因为它已更新,返回非可选的,并且不会在扩展程序中包装这种简单的操作。
Jano '18

8

Swift 5.1Xcode 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
    }

}

这很好用,确实是简洁的代码,并提供了极大的帮助。
raddevus

7

迅捷3/4 / 5.1

这是一个简单的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 } 

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

//用于字符串到字典

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
}

2

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

它总是返回零。你能帮忙吗?
Pawan

1

斯威夫特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)")
    }
}

0

SwiftyBase64(完全公开:我写了它)是一种本机Swift Base64编码(无解码库。有了它,您可以编码标准Base64:

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

或URL和文件名Safe Base64:

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

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)")
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.