How can i display animated svg file in iOS without using UIWebView

Mihir Mehta picture Mihir Mehta · Jul 4, 2017 · Viewed 8.8k times · Source

Currently i am using UIWebView to display animated svg file in my native iOS application.

This works fine except the CPU usage is constantly being on higher side as long as app is in foreground.

Is there any better way to display svg file without using UIwebView

I have already tried many third party libraries but all works only with static svg file not animated svgs

I have tried following

https://github.com/mchoe/SwiftSVG

https://github.com/exyte/Macaw

https://github.com/onmyway133/Snowflake

https://github.com/SVGKit/SVGKit

My app supports iOS 9 and above , My code is in Swift3

Here is the link of on of the svg file that i am trying to display

http://www.mediafire.com/file/04ojy6t4e3c41lv/03d.svg

Answer

Ketan Parmar picture Ketan Parmar · Jul 4, 2017

You should take look at SVGKit !

This library is based on core animation.

Refer this tutorial,

First install pod or manually install SVGKit into your project.

Then drag and drop your svg file in to your project.

Then you can do something like,

  UIView *myView = [[UIView alloc]initWithFrame:CGRectMake(20, 70, 300, 300)];

myView.backgroundColor = [UIColor yellowColor];

[self.view addSubview:myView];

 // SVGKImage *image = [SVGKImage imageWithContentsOfFile:@"animated-svg-icon"];

SVGKImage *image = [SVGKImage imageNamed:@"cd-icon.svg"];

[self animateCALayer:image.CALayerTree duration:2.0];
[myView.layer addSublayer:image.CALayerTree];

here cd-icon.svg is the svg image. Put all the html,js and css files with it in your bundle! (put whole folder of svg in your project)

If you get any error related CocoaLumberjack then install pod 'CocoaLumberjack' in your project and replace @import CocoaLumberjack; with #import "CocoaLumberjack.h" in SVGKit-prefix.pch

Follow everything step by step as I mentioned. And you are done. You will displaying svg in UIView instead of webview.