要使用Swift 5从URL获取HTML代码,你可以使用URLSession来发起网络请求并获取数据。以下是一个简单的示例代码:
import Foundation
func fetchHTML(from urlString: String, completion: @escaping (Result<String, Error>) -> Void) {
guard let url = URL(string: urlString) else {
completion(.failure(NSError(domain: "", code: -1, userInfo: [NSLocalizedDescriptionKey: "Invalid URL"])))
return
}
let task = URLSession.shared.dataTask(with: url) { data, response, error in
if let error = error {
completion(.failure(error))
return
}
guard let data = data else {
completion(.failure(NSError(domain: "", code: -1, userInfo: [NSLocalizedDescriptionKey: "No data received"])))
return
}
if let htmlString = String(data: data, encoding: .utf8) {
completion(.success(htmlString))
} else {
completion(.failure(NSError(domain: "", code: -1, userInfo: [NSLocalizedDescriptionKey: "Failed to convert data to string"])))
}
}
task.resume()
}
// 使用示例
let urlString = "https://www.example.com"
fetchHTML(from: urlString) { result in
switch result {
case .success(let html):
print("HTML: \(html)")
case .failure(let error):
print("Error: \(error.localizedDescription)")
}
}
通过以上代码和解释,你应该能够理解如何使用Swift 5从URL获取HTML代码,并处理可能遇到的问题。
领取专属 10元无门槛券
手把手带您无忧上云