如何获取网站 Favicon:三种方法详解
获取网站的 Favicon,可以使用以下几种方法:
-
直接访问网站的根目录,通常会在根目录下找到名为'favicon.ico'的文件。例如,访问https://www.google.com/favicon.ico,可以直接获取 Google 的 Favicon。
-
使用第三方 Favicon API。例如,FaviconKit 提供了一个简单的 API,可以使用以下代码获取任何网站的 Favicon:
import FaviconKit
let url = URL(string: 'https://www.google.com')
let favicon = FaviconKit.fetchFavicon(for: url)
- 使用网站的 HTML 头信息。Favicon 通常会在网站的 HTML 头信息中指定,可以使用以下代码获取网站的 HTML 头信息:
let url = URL(string: 'https://www.google.com')
let task = URLSession.shared.dataTask(with: url!) { (data, response, error) in
if error == nil {
if let httpResponse = response as? HTTPURLResponse {
if let contentType = httpResponse.allHeaderFields['Content-Type'] as? String {
if contentType.contains('text/html') {
if let html = String(data: data!, encoding: .utf8) {
// 解析 HTML 头信息获取 Favicon
}
}
}
}
}
}
task.resume()
原文地址: https://www.cveoy.top/t/topic/mY9L 著作权归作者所有。请勿转载和采集!