Swift: 如何在NSURL中引用本地图片

Swift: How to reference local image in NSURL

我有一个代码可以从在线检索的文章中加载一些缩略图并将它们放入 Article 对象中。看起来像下面这样:

            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)

然而,当一篇文章没有缩略图时就会出现问题,因此我必须使用本地图像。没有缩略图的本地文件称为 no-thumbnail.png,但是我似乎无法在线找到有关如何通过在 [=] 中使用 NSURL 实际引用本地文件(在本例中为 .png 图像)的简单指南27=].

找人分享对此的一些见解。

解决方案

对于感兴趣的人,解决方案如下:

let th = NSBundle.mainBundle().URLForResource("no-thumbnail", withExtension: "png")
url = th!.absoluteString

您可以使用Bundle.main.url(forResource: "no-thumbnail", withExtension: "png")

Swift 4:

的语法略有变化

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