Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift: How to reference local image in NSURL

I have a code which loads some thumbnails from articles retrieved online and places them into an Article object. It looks like the following:

            for article in newArticlesArray {
                let url: String
                if let myGroup = article["group"] as? Dictionary<NSObject, AnyObject>, let myThumbnail = myGroup["thumbnail"] as? Dictionary<NSObject, AnyObject>, let myURL = myThumbnail["url"] as? String{
                    url = myURL
                }
                else{
                    url = "file://no-thumbnail.png"
                }

            let a = Article(t: article["title"] as! String,
                                    da: article["pubDate"] as! String,
                                    de: newDesc,
                                    th: NSURL(string: url)!,
                                    l: NSURL(string: article["link"] as! String)!)
                    articlesArray.addObject(a)

However the issue arises when an article does not have a thumbnail and hence I have to use a local image. The local file for no thumbnail is called no-thumbnail.png, however I cannot seem to find a simple guide online on how to actually reference a local file, in this case a .png image, through the usage of an NSURL in swift.

Looking for somebody to share some insight into this.

Solution

For people interested the solution is as follows:

let th = NSBundle.mainBundle().URLForResource("no-thumbnail", withExtension: "png")
url = th!.absoluteString
like image 409
Big Green Alligator Avatar asked Apr 20 '16 23:04

Big Green Alligator


2 Answers

You can use Bundle.main.url(forResource: "no-thumbnail", withExtension: "png")

like image 96
rounak Avatar answered Oct 27 '22 10:10

rounak


The syntax has changed a bit for Swift 4:

let imageURL = Bundle.main.url(forResource: "imageName", withExtension: "png")

like image 26
JaredH Avatar answered Oct 27 '22 10:10

JaredH