Grab Web Content in Swift

604 Views Asked by At

I have created this task to grab some content from the web:

let task = NSURLSession.sharedSession().dataTaskWithURL(url!, completionHandler: { (data, response, error) -> Void in

            if error == nil {

                var urlContent = NSString(data: data, encoding: NSUTF8StringEncoding) as NSString!

                // Get the part that you are interested in from the web page

                var urlContentArray = urlContent.componentsSeparatedByString("<div class=\"entry-summary\" itemprop=\"text\">")

                // Check if the array contains a value before you print

                if urlContentArray.count > 0 {

                    var newsArray = urlContentArray[1].componentsSeparatedByString("</div>")

                    var news = newsArray[0] as String

                    self.webView.loadHTMLString(news, baseURL: nil)

                    self.webContentLabel.text = news

                }

            } else {

                println("Error")

            }

        })

My problem is that the website is formated so that there is a lot of space between the string I'm grabbing first and the <p> that contains the text I'm interested in, hence I get the <p> in the beginning of the grabbed text. If I add the <p> at the end of the string I'm grabbing I get an error saying that the array is empty. I think that the reason for this is the space between "...itemprop="text">" and "<p>" in the actual html file?

Any ideas?

0

There are 0 best solutions below