get metadata from url in swift

To extract metadata from a website URL in Swift, you can use the SwiftSoup library. Here's an example code snippet that demonstrates how to use this library to get metadata from a website URL:

main.swift
import SwiftSoup

guard let url = URL(string: "https://www.example.com") else { return }

do {
    let html = try String(contentsOf: url)
    let doc = try SwiftSoup.parse(html)
    let title = try doc.title()
    let description = try doc.select("meta[name=description]").first()?.attr("content") ?? ""
    let image = try doc.select("meta[property=og:image]").first()?.attr("content") ?? ""
    
    print("Website title: \(title)")
    print("Description: \(description)")
    print("Image URL: \(image)")
} catch Exception.Error(_, let message) {
    print(message)
} catch {
    print("error")
}
601 chars
20 lines

In this code, we first create a URL object representing the website URL that we want to extract metadata from. We then use the String(contentsOf:) method to retrieve the HTML content from the URL.

We then create a SwiftSoup document object from the HTML content and use various methods of the doc object to extract the metadata that we're interested in – the website title, description and image URL.

Once we've extracted the metadata, we print out the values for testing purposes. You could easily modify this code to use the extracted metadata for other purposes, such as displaying the website information in a custom view.

gistlibby LogSnag