如何在 swift 2.2 中的某些站点中显示来自 html 源的图像?
实际上我没有任何 JSON 或 XML。
重要的是我必须使用正则表达式。
我试过这个:
if htmlContent != nil
{
let htmlContent = (item?.htmlContent)! as NSString
var imageSource = ""
let rangeOfString = NSMakeRange(0, htmlContent.length)
let regex = try! NSRegularExpression(pattern: "(<img.*?src=\")(.*?)(\".*?>)", options: [.CaseInsensitive])
if htmlContent.length > 0
{
let match = regex.firstMatchInString(htmlContent as String, options: [.WithTransparentBounds], range: rangeOfString)
if match != nil
{
let imageURL = htmlContent.substringWithRange(match!.rangeAtIndex(2)) as NSString
print(imageURL)
if NSString(string: imageURL.lowercaseString).rangeOfString("feedBurner").location == NSNotFound
{
imageSource = imageURL as String
}
}
}
if imageSource != ""
{
imgHTMLLoader.setImageWithURL(NSURL(fileURLWithPath: imageSource), placeholderImage: UIImage(named: "placeholder"))
print("placeholderImage is not! nil")
}
else
{
imgHTMLLoader.image = UIImage(named: "placeholder")
print("placeholderImage is nil")
}
}
在此示例(库)中...htmlContent 始终为 nil。
这个示例,使用“Helper library”但它不起作用...
谢谢
最佳答案
使用 SwiftSoup第三方库和 Swift 3.0
let doc = try SwiftSoup.parse("<div id=div1><p>Hello</p><p>Another <b>element</b></p><div id=div2><img src=foo.png></div></div>");
for element in try doc.select("img").array(){
try print(element.attr("src"))
}
//foo.png
关于html - Swift:如何显示来自 html 源的图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40692622/