A.A
A.A

Reputation: 25

Swift: how to display image from html source

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

Upvotes: 1

Views: 4420

Answers (1)

Scinfu
Scinfu

Reputation: 1131

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

Upvotes: 2

Related Questions