Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get a URL "title" tag value?

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?

like image 201
Hreno Hrenovich Avatar asked Nov 09 '22 18:11

Hreno Hrenovich


1 Answers

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 ;)

like image 59
Thomas Avatar answered Nov 28 '22 08:11

Thomas