将Base64string转换为字符串的问题

时间:2019-06-19 06:19:02

标签: ios swift

我试图将base64字符串转换为字符串格式,但我总是得到nil。我的base64字符串为 “NWQwMDU2ZjhiZjRjYmI2M2MxZTI0NzQzNjAxMjMxMzAyMDh8NjAxMjMxMzAyMDh8NWQwMDU2Zjhi \ nZjRjYmI2M2MxZTI0NzQzfDYwMTIzMTMwMjA4fG5hdmlnYXRpb25UZXN0MDA1fDIwMTktMDYtMjEg \ nMDk6MzQ6MDB8MA == \ n” 个

解码后,看起来像这样的“ 5d0056f8bf4cbb63c1e2474360123130208 | 60123130208 | 5d0056f8bэ͌Ŕ٥ѥQشĂs3C。”。 这是我的代码事件,我尝试从字符串中删除“ = \ n”,但未成功。

 func qrScanningSucceededWithCode(_ str: String?) {
    scanTicketView.qrData = QRData(codeString: str)
    let charsToRemove: Set<Character> = Set("=\n")
    let newNumberCharacters = String(str!.filter { !charsToRemove.contains($0) })
    let decodedString = String(data: Data(base64Encoded: newNumberCharacters)!, encoding: .utf8)!
    print(decodedString)
}

1 个答案:

答案 0 :(得分:0)

这有效:

let string = "NWQwMDU2ZjhiZjRjYmI2M2MxZTI0NzQzNjAxMjMxMzAyMDh8NjAxMjMxMzAyMDh8NWQwMDU2Zjhi\nZjRjYmI2M2MxZTI0NzQzfDYwMTIzMTMwMjA4fG5hdmlnYXRpb25UZXN0MDA1fDIwMTktMDYtMjEg\nMDk6MzQ6MDB8MA==\n"

let joined = string.replacingOccurrences(of: "\n", with: "")

if let data = Data(base64Encoded: joined) {
    String(data: data, encoding: .utf8)
}