How can I encode a string to Base64 in Swift?

前端 未结 15 755
情歌与酒
情歌与酒 2020-11-28 02:30

I want to convert a string to Base64. I found answers in several places, but it does not work anymore in Swift. I am using Xcode 6.2. I believe the answer might be work in p

15条回答
  •  孤城傲影
    2020-11-28 02:57

    Swift 4.2

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

    to decode, see (from 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)")
        }
    }
    

提交回复
热议问题