Difference between revisions of "Swift Code Fragments"
Jump to navigation
Jump to search
PeterHarding (talk | contribs) |
PeterHarding (talk | contribs) |
||
Line 52: | Line 52: | ||
let url = URL(string: myUrl) | let url = URL(string: myUrl) | ||
</pre> | </pre> | ||
=URMLs= | |||
<pre> | |||
let myURLString = "https://google.com" | |||
guard let myURL = URL(string: myURLString) else { | |||
print("Error: \(myURLString) doesn't seem to be a valid URL") | |||
return | |||
} | |||
do { | |||
let myHTMLString = try String(contentsOf: myURL, encoding: .ascii) | |||
print("HTML : \(myHTMLString)") | |||
} catch let error { | |||
print("Error: \(error)") | |||
} | |||
</pre> | |||
[[Category:Swift]] | [[Category:Swift]] |
Revision as of 11:55, 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)
URMLs
let myURLString = "https://google.com" guard let myURL = URL(string: myURLString) else { print("Error: \(myURLString) doesn't seem to be a valid URL") return } do { let myHTMLString = try String(contentsOf: myURL, encoding: .ascii) print("HTML : \(myHTMLString)") } catch let error { print("Error: \(error)") }