我有一个代码,可以从在线检索的文章中加载一些缩略图,并将它们放入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
,但我似乎无法在线找到关于如何通过在swift中使用NSURL来实际引用本地文件(在本例中为.png图像)的简单指南。
寻找有人对此分享一些见解。
解决方案
对于感兴趣的人,解决方案如下:
let th = NSBundle.mainBundle().URLForResource("no-thumbnail", withExtension: "png")
url = th!.absoluteString
答案 0 :(得分:4)
您可以使用NSBundle.mainBundle.URLForResource("no-thumbnail", withExtension: "png")
答案 1 :(得分:1)
Swift 4 的语法已更改:
let imageURL = Bundle.main.url(forResource: "imageName", withExtension: "png")