Swift - Parse in HTML

1

I currently have a project for IOS 9 where I have a UIWebView component, I'm retrieving a webpage and submitting within this component.

But my goal is to get only the first form that is presented inside the HTML, that is, I want to return only the HTML of the first form and present it in UIWebView formatted as a web page. Any ideas how to do this?

    
asked by anonymous 16.10.2015 / 18:18

1 answer

3

Hello.

You can use the hpple framework for this. The framework is built on Objective-C, but you can use it in Swift. I made a simple example, which loads an HTML page with two forms (distributed along with the app), parse the HTML and show only the first form.

This is the HTML page:

<!DOCTYPE HTML>
<html>
    <head>
        <title>Test page with 2 forms</title>
    </head>
    <body>
        <h1>Form 1</h1>
        <form id="form1" action="your_action_here">
            <input type="text" value="You name here">
            <input type="submit">
        </form>

        <h1>Form 2</h1>
        <form id="form2">
            <input type="text" value="You name here">
            <input type="submit">
        </form>
    </body>
</html>

I made a simple ViewController, which finds and loads the first HTML form in the viewDidLoad method.

import UIKit
import hpple

class ViewController: UIViewController {

    @IBOutlet weak var webView: UIWebView!

    override func viewDidLoad() {
        super.viewDidLoad()

        if let htmlFile = NSBundle.mainBundle().pathForResource("index", ofType: "html", inDirectory: "www") {
            let htmlData = NSData(contentsOfFile: htmlFile)
            let htmlDocument = TFHpple(HTMLData: htmlData)
            if let htmlElements = htmlDocument.searchWithXPathQuery("//form[@id='form1']") as? [TFHppleElement] {
                if let firstForm = htmlElements.first?.raw {
                    webView.loadHTMLString(firstForm, baseURL: nil)
                }
            }
        } else {
            print("File not found")
        }
    }
}

You can see the full source code in this repository in GitHub . I used CocoaPods to add hpple dependency. If you want more information about CocoaPods, you can view this tutorial .

    
17.10.2015 / 22:23