如何在快速编码string到base64

我想将一个string转换为一个base64。 我在几个地方find了同样的答案,但是它不能很快地工作。 我正在使用Xcode 6.2。 我相信答案可能是以前的Xcode而不是Xcode 6.2。

有人可以请指导我在Xcode 6.2中做到这一点?

我find的答案是这样的。 但在Xcode 6.2中不起作用

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

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

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

dataUsingEncoding返回一个可选项,所以你需要解开这个。

NSDataBase64EncodingOptions.fromRaw已被replace为NSDataBase64EncodingOptions(rawValue:) 。 有点令人惊讶的是,这不是一个可靠的初始化器,所以你不需要解开它。

但是由于NSData(base64EncodedString:) 一个failable的初始化器,你需要解开这个。

顺便说一句,所有这些更改都是由Xcode migratorbuild议的(单击错误消息的排水沟,它有一个“修复它”的build议)。

最终的代码,重写,以避免暴力,看起来像这样:

 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 3

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

Swift 2.3

 import UIKit extension String { func fromBase64() -> String? { guard let data = NSData(base64EncodedString: self, options: NSDataBase64DecodingOptions(rawValue: 0)) else { return nil } return String(data: data, encoding: NSUTF8StringEncoding) } func toBase64() -> String? { guard let data = self.dataUsingEncoding(NSUTF8StringEncoding) else { return nil } return data.base64EncodedStringWithOptions(NSDataBase64EncodingOptions(rawValue: 0)) } } 

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

 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及更高版本

经过深入研究,我find了解决办法

编码

  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/

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 

Swift 3

这里是一个简单的String扩展更新为Swift 3,允许在解码时保留可选的错误。

 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 } 

经过一番斗争,我做到了这一点。

 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 

我调用另一个函数将解码的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 } 

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

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) 

@ Swift 2.0中的空速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)") 

在Swift 3中,你可以这样做:

 let base64Encoded = Data(str.utf8).base64EncodedString()