SVGKit iOS loading of image

3.2k Views Asked by At

I've imported SVGKit lib into my project and I would like to load svg image that I have stored in NSString like that:

<svg xmlns="http://www.w3.org/2000/svg" ....
</svg>

When I try to load it via

SVGKImage* newImage = [SVGKImage imageWithContentsOfURL:svgUrl];

I get err because the url is nil, thats obvious because it isn't URL, but is there any method in library that I can use??

3

There are 3 best solutions below

2
On

You need to create a NSURL object from the string representation of the URL, so:

NSString *strURL = "http://......";

NSURL *imageURL = [[NSURL alloc] initWithString:strURL];

SVGKImage *svgImage = [SVGKImage imageWithContentsOfURL:imageURL];

Does that help?

1
On

You can do this:

NSData* svgData = [svgSource dataUsingEncoding: NSUTF8StringEncoding];
SVGKImage *svgImage = [SVGKImage imageWithData:svgData];

However, I suspect that what you should be doing is what Zhang is suggesting. In any case, you should make sure that when you download the data you do it off the main thread.

0
On

Using the SVGKit 2.x, you can use the SVGKLayeredImageView and load the image from URL: (My sample code in Swift Xcode 7.1)

  1. In Interface Builder, drag a "View" into the your Scene.
  2. Go to Identity Inspector and change that Custom Class of that view is SVGKLayeredImageView (If the class is not available and you do not see it here, that means you do not import SVGKit the same version I have or do not install the framework properly)

  3. Make outlet connection of that view then you should have

@IBOutlet weak var svgImageView: SVGKLayeredImageView!

  1. Usage

      if let url = NSURL(string: "http://your-svg-file-url"){
            if url.pathExtension!.lowercaseString == "svg" {
    
                svgImageView.image = SVGKImage(contentsOfURL: url)
    
            }
        }