How can I encode a string to Base64 in Swift?

前端 未结 15 752
情歌与酒
情歌与酒 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:51

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

提交回复
热议问题