如何将 UUID 转换为 base64,反之亦然

How to convert UUID to base 64 and vise versa

我有以下扩展来将 UUID 转换为 base64 url 安全字符串,反之亦然。我正在努力解决 base64UrlSafeString 不返回 utf8 字符串的问题,因为底层数据是一个 UInt8 数组。至少我认为这是问题所在,因为 decodeBase64UrlSafeString() returns 的最后一行为零。有没有一种安全的方法可以将 UUID 中的 16 个字节转换为具有 utf8 编码的 Data 对象?

let uuid = UUID(uuidString: "9823c260-4feb-11e9-990c-354fb53401ce")!
print(uuid.base64UrlSafeString) //mCPCYE_rEemZDDVPtTQBzg
print(UUID.decodeBase64UrlSafeString(uuid.base64UrlSafeString)) //nil

UUID 扩展:

extension UUID {
    var base64UrlSafeString: String {
        var result = self.data.base64EncodedString()
        result = result.replacingOccurrences(of: "+", with: "-")
        result = result.replacingOccurrences(of: "/", with: "_")
        result = result.replacingOccurrences(of: "=", with: "")
        return result
    }
    var data: Data {
        var result = Data()
        result.append(uuid.0)
        result.append(uuid.1)
        result.append(uuid.2)
        result.append(uuid.3)
        result.append(uuid.4)
        result.append(uuid.5)
        result.append(uuid.6)
        result.append(uuid.7)
        result.append(uuid.8)
        result.append(uuid.9)
        result.append(uuid.10)
        result.append(uuid.11)
        result.append(uuid.12)
        result.append(uuid.13)
        result.append(uuid.14)
        result.append(uuid.15)
        return result
    }
    static func decodeBase64UrlSafeString(_ base_64_uuid: String ) -> String? {
        var base_64_uuid = base_64_uuid
        base_64_uuid = base_64_uuid.replacingOccurrences(of: "-", with: "+")
        base_64_uuid = base_64_uuid.replacingOccurrences(of: "_", with: "/")
        while base_64_uuid.count % 4 != 0 {
            base_64_uuid = base_64_uuid.appending("=")
        }
        guard let data = Data(base64Encoded: base_64_uuid) else { return nil }
        print("Got here") //code makes it here
        return String(data: data, encoding: .utf8) //returns nil!
    }
}

UUID 数据不是有效的 utf8 编码字符串。您需要的是将数据转换为 UUID,然后 return uuidString:

static func decodeBase64UrlSafeString(_ base_64_uuid: String) -> String? {
    var base_64_uuid = base_64_uuid
        .replacingOccurrences(of: "-", with: "+")
        .replacingOccurrences(of: "_", with: "/")
    while base_64_uuid.count % 4 != 0 { base_64_uuid += "=" }
    guard let data = Data(base64Encoded: base_64_uuid), data.count == 16 else { return nil }
    let uuid = data.withUnsafeBytes { [=10=].load(as: UUID.self) }
    return uuid.uuidString
}