Swift: how to display image from html source

|▌冷眼眸甩不掉的悲伤 提交于 2021-02-08 10:38:29

问题


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

Actually I don't have any JSON or XML.

The important thing is that I have to use regex.

I tried this:

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")
    }

}

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

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

thanks


回答1:


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


来源:https://stackoverflow.com/questions/40692622/swift-how-to-display-image-from-html-source

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!