Difference between revisions of "Swift Code Fragments"
Jump to navigation
Jump to search
PeterHarding (talk | contribs) (Created page with " From: https://stackoverflow.com/questions/31080818/what-is-the-best-practice-to-parse-html-in-swift <pre> let file = "file.txt" if let dirs : [String] = NSSearchPathForDire...") |
PeterHarding (talk | contribs) |
||
| Line 44: | Line 44: | ||
</pre> | </pre> | ||
=% Encoding URL Args= | |||
<pre> | |||
var myUrl = "http://myurl.com" | |||
myUrl = myUrl.addingPercentEncoding(withAllowedCharacters: .urlFragmentAllowed)! | |||
let url = URL(string: myUrl) | |||
</pre> | |||
[[Category:Swift]] | [[Category:Swift]] | ||
Revision as of 11:52, 14 January 2019
From: https://stackoverflow.com/questions/31080818/what-is-the-best-practice-to-parse-html-in-swift
let file = "file.txt"
if let dirs : [String] = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.AllDomainsMask, true) as? [String] {
let dir = dirs[0] //documents directory
let path = dir.stringByAppendingPathComponent(file);
let html = String(contentsOfFile: path, encoding: NSUTF8StringEncoding, error: nil)
Edit:
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
}
}
shareimprove this answer
% Encoding URL Args
var myUrl = "http://myurl.com" myUrl = myUrl.addingPercentEncoding(withAllowedCharacters: .urlFragmentAllowed)! let url = URL(string: myUrl)