Convert base64 string to uiimage iOS swift
Problem:
I'm having base 64 string with me.I want an extension function that will convert the base 64 string UIImage.
Solution:
extension String {
func base64ToImage() -> UIImage? {
if let url = URL(string: self),let data = try? Data(contentsOf: url),let image = UIImage(data: data) {
return image
} else {
if let imageData = NSData(base64Encoded: self, options: NSData.Base64DecodingOptions.ignoreUnknownCharacters) {
return UIImage(data: imageData as Data)
} else {
let str = self.replacingOccurrences(of: "data:image/svg+xml;base64,", with: "")
if let imageData = Data(base64Encoded:str) {
if let anSVGImage: SVGKImage = SVGKImage(data:imageData) {
anSVGImage.caLayerTree.backgroundColor = UIColor.clear.cgColor
return anSVGImage.uiImage
}
}
}
}
return nil
}
}
Call the function as like below
myimageview.image = mystring.base64ToImage()
Comments
Post a Comment