I need to get title of page user entered.
URL can be entered as "http://url.com"
or as "url.com"
Also, server can redirect straight request to it (checked on "google.com"
)
How should I correctly make a request and get a value between <title>
and </title>
tags of response?
You have to parse the HTML page your user request.
Try an HTML parser like Kanna
Once you have installed Kanna via cocoapods, try this code:
import Kanna
let html = "<html>...</html>"
if let doc = Kanna.HTML(html: html, encoding: NSUTF8StringEncoding) {
print(doc.title) // here your title
}
To get HTML code from a page, try this request:
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")
}
Hope it helps ;)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With