Skip to content

Instantly share code, notes, and snippets.

@robertmryan
Last active February 5, 2022 03:46
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save robertmryan/6eeb9b1b94cc1392457c2017a07dd1ae to your computer and use it in GitHub Desktop.
Save robertmryan/6eeb9b1b94cc1392457c2017a07dd1ae to your computer and use it in GitHub Desktop.
struct HoundResponse<T: Decodable>: Decodable {
var message: T?
var status: String
}
let url = URL(string: "https://dog.ceo/api/breed/hound/images")!
URLSession.shared.dataTask(with: url) { data, _, error in
guard let data = data, error == nil else {
print(error ?? URLError(.badServerResponse))
return
}
do {
let result = try JSONDecoder().decode(HoundResponse<[URL]>.self, from: data)
print(result)
} catch let parseError {
print(parseError)
}
}.resume()
@robertmryan
Copy link
Author

robertmryan commented Feb 5, 2022

Or, if you wanted a single random image:

let url = URL(string: "https://dog.ceo/api/breed/hound/images/random")!
URLSession.shared.dataTask(with: url) { data, _, error in
    guard let data = data, error == nil else {
        print(error ?? URLError(.badServerResponse))
        return
    }

    do {
        let result = try JSONDecoder().decode(HoundResponse<URL>.self, from: data)
        print(result)
    } catch let parseError {
        print(parseError)
    }
}.resume()

Note, I added /random to the end of the URL, but used Response<URL> (not an array).

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment