How can I load SVG files from URL and use it as UIImage?

Viewed 5770

With Xcode 12 release, now SVG assets are supported.

It is fine if I want to use SVG in my asset catalog. But it doesn't work when I try to load it from an URL any idea?

let downloadURL = URL.init(string:"https://www.flaticon.com/svg/static/icons/svg/3874/3874453.svg")
image.af.setImage(withURL: downloadURL!,imageTransition: .crossDissolve(0.5))
1 Answers

First, your description of the frameworks you'd like to use is very unclear. It's hard to imagine what image.af.setImage is.
There're third-party frameworks which support SVG, e.g. https://github.com/mchoe/SwiftSVG.
But I assume you're interested in SDK solutions.

Second, you should define what to you mean by "asset". Generally, in Xcode an asset is a resource file build into app, so there's no need to download it from URL.

1. You can easily load an SVG with WebKit:

let path = "https://www.flaticon.com/svg/static/icons/svg/3874/3874453.svg"
let webView = WKWebView(frame: view.bounds)
let request = URLRequest(url: URL(string: path)!)
webView.load(request)
view.addSubview(webView)

2. If you're considering a framework other than WebKit, you can load that image as Data, and then pass that Data to your framework:

let path = "https://www.flaticon.com/svg/static/icons/svg/3874/3874453.svg"
let data = try! Data(contentsOf: URL(string: path)!)

3. You can save an SVG as a "resource", and load that local resource. This is the optimal way.

let path = Bundle.main.path(forResource: "3874453", ofType: "svg")!
let webView = WKWebView(frame: view.bounds)
let request = URLRequest(url: URL(fileURLWithPath: path)!)
webView.load(request)
view.addSubview(webView)

The full code looks like this:

import UIKit
import WebKit

class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        
        let webView = WKWebView(frame: view.bounds)
        let request = URLRequest(url: svgUrlLocal)
        //let request = URLRequest(url: svgUrlRemote)
        webView.load(request)
        view.addSubview(webView)
    }
    
    var svgUrlLocal: URL {
        let path = Bundle.main.path(forResource: "3874453", ofType: "svg")!
        return URL(fileURLWithPath: path)
    }
    
    var svgUrlRemote: URL {
        let path = "https://www.flaticon.com/svg/static/icons/svg/3874/3874453.svg"
        return URL(string: path)!
    }
}

You can download the project here: https://github.com/gatamar/stackoverflow_answers/tree/master/so65266899

Related