TEAM LICENSES: Save money and learn new skills through a Hacking with Swift+ team license >>

Converting Base64 decoded SVG Image to Image always returns nil

Forums > SwiftUI

@nando  

Hello,

i am searching a way to decode a Base64 decoded SVG Image and display it with the swift Image component.

I always get nil when trying to convert my decoded data to an Image.

func convertBase64StringToImage (imageBase64String: String) -> UIImage {
    print("imageBase64String: ", imageBase64String)
    var rawbase64String = imageBase64String

    if imageBase64String.contains("data:image/svg+xml;base64,") {
        print("incoming avatar is SVG")
        rawbase64String = imageBase64String.replacingOccurrences(of: "data:image/svg+xml;base64,", with: "")
    }
    else {
        print("incoming avatar has unknown file type")
        rawbase64String = defaultAvatar()
    }

    print ("Using avatar: ", rawbase64String)
    let dataDecoded = Data(base64Encoded: rawbase64String)
    let decodedImage = UIImage(data: dataDecoded!)
    print ("decodedImage: ", decodedImage)
    return decodedImage!
}

decodedImage gets always nil

Any ideas?

Greetings Nando

1      

You cannot initialize a UIImage from an SVG like that. The only way to use an SVG with UIImage is if the SVG is already in your assets catalog.

1      

@nando  

Really sad...

So there is no way to display SVG which i receive in base64 string ? Or is it maybe possible to save base64 SVG string in assets programatically and the use it?

Greetings Nando

1      

Not natively in a UIImage. You can use a third party package, like SVGKit, or you could try displaying your SVG in a WKWebView.

1      

Hacking with Swift is sponsored by Blaze.

SPONSORED Still waiting on your CI build? Speed it up ~3x with Blaze - change one line, pay less, keep your existing GitHub workflows. First 25 HWS readers to use code HACKING at checkout get 50% off the first year. Try it now for free!

Reserve your spot now

Sponsor Hacking with Swift and reach the world's largest Swift community!

Archived topic

This topic has been closed due to inactivity, so you can't reply. Please create a new topic if you need to.

All interactions here are governed by our code of conduct.

 
Unknown user

You are not logged in

Log in or create account
 

Link copied to your pasteboard.