F
F
Fenkins2015-03-29 19:09:59
Swift
Fenkins, 2015-03-29 19:09:59

Does HTML parsing with Swift-HTML-Parser work for real websites?

I'm new to programming in general and Swift in particular, however I've taken a couple of courses and wanted to make a very simple application that would get news from a website and add it to a tableView.
At the moment I'm getting an error:

Optional(Error Domain=HTMLParserdomain Code=1 "The operation couldn't be completed. (HTMLParserdomain error 1.)")

The code written is quite simple, it is an example from the tid-kijyun repository plus code that gets the contents of the HTML file received by the link.
func perFormConnectionToGrabUrlContent(# url:String)-> NSString {
            let url = NSURL(string: url)
            let request = NSURLRequest(URL: url!)
            var htmlContentTemp:NSString = ""
            NSURLConnection.sendAsynchronousRequest(request, queue: NSOperationQueue.mainQueue()) {(response, data, error) in
                htmlContentTemp = NSString(data: data, encoding: NSUTF8StringEncoding)!
                println(htmlContentTemp)
            }
            return htmlContentTemp
        }


        let html = perFormConnectionToGrabUrlContent(url: "http://www.google.com")
        println(html)

        var err : NSError?
        var parser     = HTMLParser(html: html, error: &err)
        if err != nil {
            println(err)
            exit(1)
        }

        var bodyNode   = parser.body

        if let inputNodes = bodyNode?.findChildTags("a") {
            for node in inputNodes {
                println(node.contents)
            }
        }

        if let inputNodes = bodyNode?.findChildTags("a") {
            for node in inputNodes {
                println(node.contents)
                println(node.getAttributeNamed("href"))
            }
        }

The question is, is it necessary to tweak something in the code, after which the program should work, or is it better to access the site database and get information by querying it? (for example)

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
DFandEL, 2015-07-28
@DFandEL

var htmlContentTemp:NSString = ""
            NSURLConnection.sendAsynchronousRequest(request, queue: NSOperationQueue.mainQueue()) {(response, data, error) in
                htmlContentTemp = NSString(data: data, encoding: NSUTF8StringEncoding)!
                println(htmlContentTemp)
            }
            return htmlContentTemp

Most likely a problem in an asynchronous request. You always give "" a string. Change to synchronous or return the response in a separate block

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question