Skip to content

Instantly share code, notes, and snippets.

@mhanlon
Last active April 11, 2022 07:30
Show Gist options
  • Save mhanlon/b6ddd8f956affa8e496d9d7423da43f1 to your computer and use it in GitHub Desktop.
Save mhanlon/b6ddd8f956affa8e496d9d7423da43f1 to your computer and use it in GitHub Desktop.
The second phase of our Advanced Xcode workshop
import UIKit
let urlString = "https://api.nasa.gov/planetary/apod"
var urlComponents = URLComponents(string: urlString)!
urlComponents.queryItems = [
"api_key": "DEMO_KEY",
"date": "2022-04-11"
].map { URLQueryItem(name: $0.key, value: $0.value) }
Task {
let (data, response) = try await URLSession.shared.data(from: urlComponents.url!)
let jsonDecoder = JSONDecoder()
if let httpResponse = response as? HTTPURLResponse, httpResponse.statusCode == 200, let photoInfo = try? jsonDecoder.decode(PhotoInfo.self, from: data) {
print(photoInfo)
}
}
struct PhotoInfo: Codable {
var title: String
var description: String
var url: URL
var copyright: String?
enum CodingKeys: String, CodingKey {
case title
case description = "explanation"
case url
case copyright
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment