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3ZlMXJnYlVLU29EMVAwVjdLaS9IcW9FTlhrRDdNYk5KQzFoTkZvRmlFU2dXZ1dJUktCYUJZaEVvRm9GaUVTZ1dnZWtJTlFFZGZPa0M5b3BaQit6M0N2UjFwRzIxNkp0TnY2dzd3RlorV3cvc1A5ODRzQnM4WGNER1hEbGdOVmtFaWtXZ1dBU0tSYUJZQklwRm9GZ0Vpa1dnV0FUL0F3QUEvLy9yWFpLVzhmMG5SQUFBQUFCSlJVNUVya0pnZ2c9PSIgd2lkdGg9IjEwMCIgaGVpZ2h0PSIxMDAiIHk9IjE2MCIgeD0iMTYwIiBjbGlwLXBhdGg9InVybCgjY2xpcCkiLz4KCiAgPHRleHQgeG1sOnNwYWNlPSJwcmVzZXJ2ZSIgdGV4dC1hbmNob3I9InN0YXJ0IiBmb250LWZhbWlseT0iTm90byBTYW5zIEpQIiBmb250LXNpemU9IjI0IiBpZD0ic3ZnXzQiIHk9IjM0MiIgeD0iMTc5IiBzdHJva2Utd2lkdGg9IjAiIHN0cm9rZT0iIzAwMCIgZmlsbD0iIzAwMDAwMCI+YXNnZGhqYWdhc2Rqa2FzZGg8L3RleHQ+CiAgPHRleHQgdHJhbnNmb3JtPSJtYXRyaXgoMTguMDU3LCAwLCAwLCA3LjM3MzIsIC04NDI5LjI0LCAtMTkxNS40NSkiIHhtbDpzcGFjZT0icHJlc2VydmUiIHRleHQtYW5jaG9yPSJzdGFydCIgZm9udC1mYW1pbHk9IidEYW5jaW5nIFNjcmlwdCciIGZvbnQtc2l6ZT0iMSIgaWQ9InN2Z183IiB5PSIyOTAuNTEwNjEiIHg9IjQ5Ny4wODEyNyIgc3Ryb2tlLXdpZHRoPSI4IiBzdHJva2U9IiMwMDAiIGZpbGw9IiNmZmYiPmU8L3RleHQ+CiA8L2c+Cjwvc3ZnPg=="

如何使用SVGKit cocoapod 库将其转换为 UIImage?

现在我只是使用:

var image: UIImage? {
    guard let imageEncodedString = imageEncodedString else {
        return nil
    }
    return SVGKImage(data: Data(base64Encoded: imageEncodedString))?.uiImage //crash here inside init
}
4

1 回答 1

0

字符串的开头不是base64,这就是它失败的原因。您需要先删除data:image/svg+xml;base64,.

你有一个数据 URI

它应该是这样的:

data:[<media type>][;base64],<data>

您目前拥有:

data:image/svg+xml;base64,theBase64Image

现在,您可以始终data:image/svg+xml;base64,从字符串中删除:

let dataURI = "data:image/svg+xml;base64,theBase64Image"
let base64String = dataURI.replacingOccurrences(of: "data:image/svg+xml;base64,", with: "")

您还可以事先检查hasPrefix()以确保它具有预期的 dataURI。您也可以使用 Regex NSScanner、 等来执行此操作。

但是,既然您期望 SVG 在 base64 中,hasPrefix()应该replacingOccurrences(of:with:)就足够了。

于 2022-01-28T17:21:48.680 回答