0

I have this line of code in my HTML page: <a href="www.myWebsite.com" rel="ibox"></a>.

How can I parse it in swift code in the best way, considering that I have not only this tag "a" but many?

Marco
  • 65
  • 11
  • 1
    did you try this https://stackoverflow.com/questions/31080818/what-is-the-best-practice-to-parse-html-in-swift – Kamran Apr 19 '18 at 05:41

2 Answers2

2

Parsing HTML in Swift typically requires a third-party framework, personally, I use SwiftSoup.

Here's how you would parse that href in Swift using SwiftSoup.

do {
   let html = "<a href=\"www.myWebsite.com\" rel=\"ibox\"></a>"
   let doc: Document = try SwiftSoup.parse(html)
   let links = try doc.select("a").map {
        try $0.attr("href")
    } // ["www.myWebsite.com"]
} catch Exception.Error(let type, let message) {
    print(message)
} catch {
    print("error")
}

Link to the documentation

In the above, the links array holds the values of all the links on a page.

Will
  • 4,942
  • 2
  • 22
  • 47
2
import Foundation

let html = "theHtmlYouWannaParse"

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("b") {
    for node in inputNodes {
        println(node.contents)
    }
}

if let inputNodes = bodyNode?.findChildTags("a") {
    for node in inputNodes {
        println(node.getAttributeNamed("href")) //<- Here you would get your files link
    }
}