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