Skip to content

Instantly share code, notes, and snippets.

@cruinh
Created June 14, 2016 14:24
Show Gist options
  • Save cruinh/f366d4855132f71195b9c5006c374ef3 to your computer and use it in GitHub Desktop.
Save cruinh/f366d4855132f71195b9c5006c374ef3 to your computer and use it in GitHub Desktop.
/**
Compatible with the iOS 10 Beta 1 Swift Playgrounds app
The code below talks to NASA's "Astronomy Picture of the Day" API endpoint to download the latest picture. After running the code, the picture is viewable by tapping the image literal that appears in the right-hand margin as indicated by a comment.
note: Must replace "YOUR API KEY" on the first line of code, with a your personally-generated NASA api key. See the following link to get your API key: https://api.nasa.gov/index.html#apply-for-an-api-key
*/
import Foundation
import UIKit
let apikey = "YOUR API KEY"
let url = URL(string: "https://api.nasa.gov/planetary/apod?api_key=\(apikey)")!
let apodJSONData = try Data(contentsOf: url)
do {
guard let apodJSON = try JSONSerialization.jsonObject(with: apodJSONData, options: JSONSerialization.ReadingOptions.allowFragments) as? [String:AnyObject]
else {
throw NSError(domain: "no json", code: 0, userInfo: nil)
}
print(apodJSON)
guard let imageURLString = apodJSON["url"] as? String
else {
throw NSError(domain: "no url in json", code: 0, userInfo: nil)
}
guard let imageURL = URL(string: imageURLString)
else {
throw NSError(domain: "json url is not a url", code: 0, userInfo: nil)
}
let imageData = try Data(contentsOf: imageURL)
let image = UIImage(data: imageData, scale: 1) //Final downloaded image --->
}
catch {
print(error)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment