I have a .svg image file I want to display in my project.
I tried using UIImageView, which works for the .png & .jpg image formats, but not for the .svg extension. Is there any way to display a .svg image using UIWebView or UIImageView ?
For using SVG, you only need to drag them in your assets folder and then you can use them in your project file by using UIImage class named constructor.
How to open an SVG file. From Chrome and Edge to Safari and Firefox, all the major browsers allow you to open SVG files these days — whether you're on a Mac or Windows. Just launch your browser and click on File > Open to choose the file you want to view. It'll then be displayed in your browser.
Use the same assets on both Android and iOS. Xcode 12 introduced support for using Scalable Vector Graphic (SVG) image assets in iOS, macOS, and iPadOS. It's one of those changes that you might have missed during WWDC 2020 as it's quite a small addition.
Supported platforms It's important to point out that SVGs are only supported on macOS 10.15 or later, iOS 13 or later, and iPadOS or later.
There is no Inbuilt support for SVG in Swift. So we need to use other libraries.
The simple SVG libraries in swift are :
1) SwiftSVG Library
It gives you more option to Import as UIView, CAShapeLayer, Path, etc
To modify your SVG Color and Import as UIImage you can use my extension codes for the library mentioned in below link,
Click here to know on using SwiftSVG library :
Using SwiftSVG to set SVG for Image
|OR|
2) SVGKit Library
2.1) Use pod to install :
pod 'SVGKit', :git => 'https://github.com/SVGKit/SVGKit.git', :branch => '2.x'
2.2) Add framework
Goto AppSettings
-> General Tab
-> Scroll down to Linked Frameworks and Libraries
-> Click on plus icon
-> Select SVG.framework
2.3) Add in Objective-C to Swift bridge file bridging-header.h :
#import <SVGKit/SVGKit.h>
#import <SVGKit/SVGKImage.h>
2.4) Create SvgImg Folder (for better organization) in Project and add SVG files inside it.
Note : Adding Inside Assets Folder won't work and SVGKit searches for file only in Project folders
2.5) Use in your Swift Code as below :
import SVGKit
and
let namSvgImgVar: SVGKImage = SVGKImage(named: "NamSvgImj")
Note : SVGKit Automatically apends extention ".svg" to the string you specify
let namSvgImgVyuVar = SVGKImageView(SVGKImage: namSvgImgVar)
let namImjVar: UIImage = namSvgImgVar.UIImage
There are many more options for you to init SVGKImage and SVGKImageView
There are also other classes u can explore
SVGRect
SVGCurve
SVGPoint
SVGAngle
SVGColor
SVGLength
and etc ...
SVG file support is added to Xcode 12.
Try this code
var path: String = NSBundle.mainBundle().pathForResource("nameOfFile", ofType: "svg")!
var url: NSURL = NSURL.fileURLWithPath(path) //Creating a URL which points towards our path
//Creating a page request which will load our URL (Which points to our path)
var request: NSURLRequest = NSURLRequest(URL: url)
webView.loadRequest(request) //Telling our webView to load our above request
You can use SVGKit for example.
1) Integrate it according to instructions. Drag&dropping the .framework file is fast and easy.
2) Make sure you have an Objective-C to Swift bridge file bridging-header.h with import code in it:
#import <SVGKit/SVGKit.h>
#import <SVGKit/SVGKImage.h>
3) Use the framework like this, assuming that dataFromInternet is NSData, previously downloaded from network:
let anSVGImage: SVGKImage = SVGKImage(data: dataFromInternet)
myIUImageView.image = anSVGImage.UIImage
The framework also allows to init an SVGKImage from other different sources, for example it can download image for you when you provide it with URL. But in my case it was crashing in case of unreachable url, so it turned out to be better to manage networking by myself. More info on it here.
You can add New Symbol Image Set in .xcassets, then you can add SVG file in it
and use it same like image.
Note: This doesn't work on all SVG. You can have a look at the apple documentation
My solution to show .svg in UIImageView from URL. You need to install SVGKit pod
Then just use it like this:
import SVGKit
let svg = URL(string: "https://openclipart.org/download/181651/manhammock.svg")!
let data = try? Data(contentsOf: svg)
let receivedimage: SVGKImage = SVGKImage(data: data)
imageview.image = receivedimage.uiImage
or you can use extension for async download
extension UIImageView {
func downloadedsvg(from url: URL, contentMode mode: UIView.ContentMode = .scaleAspectFit) {
contentMode = mode
URLSession.shared.dataTask(with: url) { data, response, error in
guard
let httpURLResponse = response as? HTTPURLResponse, httpURLResponse.statusCode == 200,
let mimeType = response?.mimeType, mimeType.hasPrefix("image"),
let data = data, error == nil,
let receivedicon: SVGKImage = SVGKImage(data: data),
let image = receivedicon.uiImage
else { return }
DispatchQueue.main.async() {
self.image = image
}
}.resume()
}
}
How to use:
let svg = URL(string: "https://openclipart.org/download/181651/manhammock.svg")!
imageview.downloadedsvg(from: svg)
let path = Bundle.main.path(forResource: "svgNameFileHere", ofType: "svg")!
if path != "" {
let fileURL:URL = URL(fileURLWithPath: path)
let req = URLRequest(url: fileURL)
self.webView.scalesPageToFit = false
self.webView.loadRequest(req)
}
else {
//handle here if path not found
}
Third party libraries
https://github.com/exyte/Macaw
https://github.com/mchoe/SwiftSVG
UIWebView and WKWebView booster to load faster
https://github.com/bernikovich/WebViewWarmUper
In case you want to use a WKWebView
to load a .svg image that is coming from a URLRequest
, you can simply achieve it like this:
Swift 4
if let request = URLRequest(url: urlString), let svgString = try? String(contentsOf: request) {
wkWebView.loadHTMLString(svgString, baseURL: request)
}
It's much simpler than the other ways of doing it, and you can also persist your .svg string somewhere to load it later, even offline if you need to.
You can keep your images as strings and use WKWebView to display them:
let webView: WKWebView = {
let mySVGImage = "<svg height=\"190\"><polygon points=\"100,10 40,180 190,60 10,60 160,180\" style=\"fill:lime;stroke:purple;stroke-width:5;fill-rule:evenodd;\"></svg>"
let preferences = WKPreferences()
preferences.javaScriptEnabled = false
let configuration = WKWebViewConfiguration()
configuration.preferences = preferences
let wv = WKWebView(frame: .zero, configuration: configuration)
wv.scrollView.isScrollEnabled = false
wv.loadHTMLString(mySVGImage, baseURL: nil)
return wv
}()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With