1

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

6
  • Welcome to StackOverflow! Can you please post, what you have tried yet? Please provide a Minimal, Complete, and Verifiable example. Commented Nov 19, 2016 at 12:00
  • Have you tried the UIWebView? Commented Nov 19, 2016 at 12:18
  • no...but is this work for my App? Commented Nov 19, 2016 at 12:20
  • i don't want load the entire of page...i want to load just image Commented Nov 19, 2016 at 12:23
  • i check UIWebView...it isnt work for this case...but thanks for your attention Commented Nov 19, 2016 at 12:40

1 Answer 1

2

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
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.