1

I need to show an SVG image, loaded from JSON, into an image view, but I have 2 issues:

  1. JSON data contains a param BODY having the SVG code as string or null

Model

  struct ResultItem: Codable{
       let id:   Int
       let players: [ResultPlayer]
       let body: String? //<------- Now it was fixed!
     }
  1. How to use the SVG string in the image? I don't want to use any external lib but Xcode12 SVG

I would like to use the SVG to replace my current code:

let storyboard = UIStoryboard(name: "Main", bundle: nil)
guard let vc = storyboard.instantiateViewController(withIdentifier: "Detail") as? DetailViewController else { return }        
vc.selectedImage = "logo_2-mini.png"
self.present(vc, animated: true)

Can you help me using a string as an SVG image?

let svg = "<svg width=\"100\" height=\"100\"><circle cx=\"50\" cy=\"50\" r=\"40\" stroke=\"green\" stroke-width=\"4\" fill=\"yellow\" /></svg>”.
Gereon
  • 17,258
  • 4
  • 42
  • 73
Uncoke
  • 1,832
  • 4
  • 26
  • 58
  • `body` is string or null? So what about making it optional? : `let body: String?` The Asset Catalogs (xcasset) can load SVG, but I'm not sure about "on the go SVG" files natively with no external lib. – Larme Feb 05 '21 at 21:46
  • 1
    Does this answer your question? [iOS : display svg from JSON](https://stackoverflow.com/questions/26360236/ios-display-svg-from-json) – Zsolt Biró Feb 05 '21 at 22:10
  • @Larme yes, optional *String?* workls, thanks! – Uncoke Feb 06 '21 at 09:53
  • @ZsoltBiró No, the answer is not correct. I use xCode12 but the link reported is corrupted (404) – Uncoke Feb 06 '21 at 09:54

1 Answers1

0

What you need is SVG support in UIImage, but we don't have that, unfortunately. The change that Xcode 12 brought was support for SVGs in Asset Catalogs, but that doesn't help when you only get the SVG data at runtime.

Depending on your exact problem, you might be able to use WKWebView to render the SVG, see e.g. How to display .svg image using swift for more details.

Otherwise, you'll have to resort to 3rd party libraries like SVGKit.

Gereon
  • 17,258
  • 4
  • 42
  • 73