Created
August 25, 2021 13:41
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
struct AlbumsFetcher { | |
enum AlbumsFetcherError: Error { | |
case invalidURL | |
case missingData | |
} | |
static func fetchAlbums(completion: @escaping (Result<[Album], Error>) -> Void) { | |
// Create URL | |
guard let url = URL(string: "https://itunes.apple.com/search?term=taylor+swift&entity=album") else { | |
completion(.failure(AlbumsFetcherError.invalidURL)) | |
return | |
} | |
// Create URL session data task | |
URLSession.shared.dataTask(with: url) { data, _, error in | |
if let error = error { | |
completion(.failure(error)) | |
return | |
} | |
guard let data = data else { | |
completion(.failure(AlbumsFetcherError.missingData)) | |
return | |
} | |
do { | |
// Parse the JSON data | |
let iTunesResult = try JSONDecoder().decode(ITunesResult.self, from: data) | |
completion(.success(iTunesResult.results)) | |
} catch { | |
completion(.failure(error)) | |
} | |
}.resume() | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment