Swift Code Fragments

From PeformIQ Upgrade
Jump to navigation Jump to search

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)

URLs

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)")
}
 let myURLString = "http://www.yahoo.com"

if let myURL = NSURL(string: myURLString) {
    var error: NSError?
    let myHTMLString = try! NSString(contentsOfURL: myURL, encoding: NSUTF8StringEncoding)

    if let error = error {
        print("Error : \(error)")
    } else {
        print("HTML : \(myHTMLString)")
    }
} else {
    print("Error: \(myURLString) doesn't  URL")
}

Swift 3:

    if let url = URL(string: "https://www.google.com/") {
        do {
            let contents = try String(contentsOf: url) {
                print(contents)
            } else {
                // Can't unwrap!
            }
        } catch {
            // contents could not be loaded
        }
    } else {
        // the URL was bad!
    }
let myURLString = "https://google.com"

let myHTMLString = try URL(string: myURLString)
    .flatMap { try Data(contentsOf: $0) }
    .flatMap { String(data: $0, encoding: .ascii) }