Swift:如何显示HTML源代码中的图像 [英] Swift: how to display image from html source

查看:65
本文介绍了Swift:如何显示HTML源代码中的图像的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在Swift 2.2的某些站点中显示来自html源的图像?

How can I display image from html source in some of sites in swift 2.2?

实际上我没有任何JSON或XML.

Actually I don't have any JSON or XML.

重要的是我必须使用正则表达式.

The important thing is that I have to use regex.

我尝试过:

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始终为零.

in this sample(library)... htmlContent always is nil.

此示例,使用帮助程序库",但不起作用...

this sample , use "Helper library" but it dosn't work...

谢谢

推荐答案

使用 SwiftSoup 第三方库和Swift 3.0

Using SwiftSoup third party library and 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

这篇关于Swift:如何显示HTML源代码中的图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆