get website image and description from url in swift

To get the website image and description from a URL in Swift, we can use web scraping techniques. Here's a sample code that uses Data and HTMLParser libraries to extract the website's title, description, and image from the HTML source code:

main.swift
import UIKit
import HTMLKit

func getWebsiteInfo(from url: URL, completion: @escaping (String?, String?, UIImage?) -> Void) {
    // Fetch HTML content
    URLSession.shared.dataTask(with: url) { data, response, error in
        guard let data = data, error == nil else {
            completion(nil, nil, nil)
            return
        }
        
        // Parse HTML
        let parser = HTMLParser(data: data)
        guard let document = parser.parseDocument() else {
            completion(nil, nil, nil)
            return
        }
        
        // Extract Page Title
        guard let pageTitle = document.head?.title?.text else {
            completion(nil, nil, nil)
            return
        }
        
        // Extract Page Description (meta property="og:description")
        let pageDescription = document.head?.children(of: "meta").first(where: { $0.attributes["property"] == "og:description" })?.attributes["content"]
        
        // Extract Page Image (meta property="og:image")
        if let imagePath = document.head?.children(of: "meta").first(where: { $0.attributes["property"] == "og:image" })?.attributes["content"],
           let imageUrl = URL(string: imagePath),
           let imageData = try? Data(contentsOf: imageUrl),
           let image = UIImage(data: imageData) {
            completion(pageTitle, pageDescription, image)
            return
        }
        
        // If no image found in meta tags, try to extract from HTML body
        let pageImages = document.body?.descendants(of: "img").compactMap { $0.attributes["src"] }
        if let imagePath = pageImages?.first,
           let imageUrl = URL(string: imagePath),
           let imageData = try? Data(contentsOf: imageUrl),
           let image = UIImage(data: imageData) {
            completion(pageTitle, pageDescription, image)
            return
        }
        
        // No image found
        completion(pageTitle, pageDescription, nil)
    }.resume()
}

// Usage:
let url = URL(string: "https://www.apple.com")!
getWebsiteInfo(from: url) { title, description, image in
    print(title, description, image)
}
2132 chars
57 lines

Note that this code only extracts the first image found on the webpage. In some cases, there may be multiple images and you may need to modify the code to extract a specific image. Also, keep in mind that web scraping may not be allowed by some websites, so use this code responsibly.

related categories

gistlibby LogSnag