Created
March 21, 2022 03:55
-
-
Save KrauserHuang/98bff2c5043ce95884fbb08d055d43c7 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var receivedData: Data? | |
func startLoad() { | |
loadButton.isEnabled = false | |
let url = URL(string: "https://www.example.com/")! | |
receivedData = Data() | |
let task = session.dataTask(with: url) | |
task.resume() | |
} | |
// delegate methods | |
func urlSession(_ session: URLSession, dataTask: URLSessionDataTask, didReceive response: URLResponse, | |
completionHandler: @escaping (URLSession.ResponseDisposition) -> Void) { | |
guard let response = response as? HTTPURLResponse, | |
(200...299).contains(response.statusCode), | |
let mimeType = response.mimeType, | |
mimeType == "text/html" else { | |
completionHandler(.cancel) | |
return | |
} | |
completionHandler(.allow) | |
} | |
func urlSession(_ session: URLSession, dataTask: URLSessionDataTask, didReceive data: Data) { | |
self.receivedData?.append(data) | |
} | |
func urlSession(_ session: URLSession, task: URLSessionTask, didCompleteWithError error: Error?) { | |
DispatchQueue.main.async { | |
self.loadButton.isEnabled = true | |
if let error = error { | |
handleClientError(error) | |
} else if let receivedData = self.receivedData, | |
let string = String(data: receivedData, encoding: .utf8) { | |
self.webView.loadHTMLString(string, baseURL: task.currentRequest?.url) | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment