Skip to content

Instantly share code, notes, and snippets.

@NickHung1982
Created November 29, 2018 20:13
Show Gist options
  • Save NickHung1982/7fa8729b0b190890f677ad09a6ed6d74 to your computer and use it in GitHub Desktop.
Save NickHung1982/7fa8729b0b190890f677ad09a6ed6d74 to your computer and use it in GitHub Desktop.
//MARK: - URLSessionDataDelegate
extension ViewController: URLSessionDataDelegate {
func urlSession(_ session: URLSession, dataTask: URLSessionDataTask, didReceive response: URLResponse, completionHandler: @escaping (URLSession.ResponseDisposition) -> Void) {
guard let httpResponse = response as? HTTPURLResponse, (200...299).contains(httpResponse.statusCode) else {
completionHandler(.cancel)
return
}
//get full lenth of your content
expectedContentLength = Int(response.expectedContentLength)
completionHandler(.allow)
}
func urlSession(_ session: URLSession, dataTask: URLSessionDataTask, didReceive data: Data) {
self.receivedData?.append(data)
//count percent and update progress
if let receivedCount = self.receivedData{
let percentageDownload = Float(receivedCount.count / self.expectedContentLength)
DispatchQueue.main.async {
self.progressView1.progress = percentageDownload
}
}
}
func urlSession(_ session: URLSession, task: URLSessionTask, didCompleteWithError error: Error?){
DispatchQueue.main.async {
self.button1.isEnabled = true
self.progressView1.progress = 1.0
if let error = error {
self.handleClientError(error)
}
//when completed receive data, put data to imageview
if let receivedData = self.receivedData {
self.imageview1.image = UIImage(data: receivedData)
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment