Last active
July 16, 2021 14:09
-
-
Save aataraxiaa/dd3412c41242245aa3991e504dcc9e26 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
func fetchData(from url: URL, withCompletion completion: @escaping (Result<ModelWrapper, Error>) -> Void) -> Void { | |
let firstTask = URLSession.shared.dataTask(with: url) { data, response, error in | |
if let error = error { | |
completion(.failure(error)) | |
// 😱 DID NOT RETURN! | |
} | |
guard let data = data else { | |
completion(.failure(APIErrors.requestError)) | |
return | |
} | |
guard let model = try? JSONDecoder().decode(Model.self, from: data) else { | |
// 😱 DID NOT CALL COMPLETION HANDLER! | |
return | |
} | |
let imageUrl = model.imageURL | |
let secondTask = URLSession.shared.dataTask(with: imageUrl) { data, response, error in | |
// 😱 PYRAMID OF DOOM STARTING TO FORM! | |
if let error = error { | |
completion(.failure(error)) | |
return | |
} | |
guard let data = data else { | |
completion(.failure(APIErrors.imageRequestError)) | |
return | |
} | |
guard let image = UIImage(data: data) else { | |
// 😱 DID NOT CALL COMPLETION HANDLER! | |
return | |
} | |
let modelWrapper = ModelWrapper(model: model, image: image) | |
completion(.success(modelWrapper)) | |
} | |
secondTask.resume() | |
} | |
firstTask.resume() | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment