Created
November 29, 2018 16:30
-
-
Save NickHung1982/e697ea8d5052c9afdcd111d852a536c5 to your computer and use it in GitHub Desktop.
This file contains 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
@IBAction func action_loadImage(_ sender: UIButton) { | |
//disable button in case user click twice | |
sender.isEnabled = false | |
//start loading image | |
startLoad() | |
} | |
func startLoad() { | |
let url = URL(string: "https://www.google.com/images/branding/googlelogo/2x/googlelogo_color_272x92dp.png")! | |
let task = URLSession.shared.dataTask(with: url) { data, response, error in | |
//if has error then return | |
if let error = error { | |
self.handleClientError(error) | |
} | |
//if status code not in 200~299 , then something happen on server side | |
guard let httpResponse = response as? HTTPURLResponse, (200...299).contains(httpResponse.statusCode) else { | |
self.handleServerError(response) | |
return | |
} | |
//load image data | |
if let mimeType = httpResponse.mimeType, mimeType == "image/png", let data = data{ | |
DispatchQueue.main.async { | |
self.imageview1.image = UIImage(data: data) | |
self.button1.isEnabled = true | |
} | |
} | |
} | |
task.resume() | |
} | |
//handle client side error here | |
func handleClientError(_ error: Error) { | |
print("client side error") | |
} | |
//handle server side error here | |
func handleServerError(_ response: URLResponse?) { | |
print("server side error") | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment