［iOS］PlaygroundでNASA（アメリカ航空宇宙局）のオープンデータを解析して、月の画像を取得する方法

# PlaygroundでNASA（アメリカ航空宇宙局）のオープンデータを解析して、月の画像を取得する方法

![MariusHills_LO2LRO_1673.jpg](https://qiita-image-store.s3.amazonaws.com/0/199441/0e101ca7-37dd-adf9-151f-8523b7d38d96.jpeg)
**【画像】**NASA（アメリカ航空宇宙局）のオープンデータから取得した、月の画像（マリウス丘）
Image Credit : Public Domain
https://apod.nasa.gov/apod/image/1710/MariusHills_LO2LRO_1673.jpg

## 共有すること
「Playgroundを使ってAPIを解析（NASAオープンデータを例に）」（2017/10/24 Qiita公開）の内容を一歩踏み込んで、Playgroundを使ってAPIをより詳細に解析する方法

## 参考資料
① [App Development with Swift - Apple](https://itunes.apple.com/jp/book/app-development-with-swift/id1219117996?mt=11)
② [Playgroundを使ってAPIを解析（NASAオープンデータを例に）](https://qiita.com/tanakadaichi_1989/items/7de6b6821395dd2a283e)

## 開発環境
Mac OS High Sierra / Swift 4.0 / Xcode 9.0

## 前提条件
NASA Open APIs（ https://api.nasa.gov/index.html#getting-started ）にアクセスの上、APIキーを取得し、下記コード例の **YOUR_API_KEY** に代入してください。

## コード例
```swift:Myplayground.playground
import UIKit
import PlaygroundSupport

PlaygroundPage.current.needsIndefiniteExecution = true

struct PhotoInfo: Codable{
    var title: String
    var description: String
    var hdurl: String

    enum Keys: String, CodingKey{
        case title = "title"
        case description = "explanation"
        case hdurl = "hdurl"
    }
    
    init(from decoder: Decoder) throws {
        let valueContainer = try decoder.container(keyedBy: Keys.self)
        self.title = try valueContainer.decode(String.self,forKey: Keys.title)
        self.description = try valueContainer.decode(String.self,forKey: Keys.description)
        self.hdurl = try valueContainer.decode(String.self,forKey: Keys.hdurl)
    }
}

let url = URL(string: "https://api.nasa.gov/planetary/apod?api_key=YOUR_API_KEY")!

let task = URLSession.shared.dataTask(with: url){
    (data, response, error) in
    let jsonDecoder = JSONDecoder()
    if let data = data,
        let photoInfo = try? jsonDecoder.decode(PhotoInfo.self, from: data){
        print("-------------")
        print(photoInfo.title)
        print("-------------")
        print(photoInfo.description)
        print("-------------")
        print(photoInfo.hdurl)
        print("-------------")
    } else {
        print("Either no data was returned, or data was not serialized.")
    }
}


task.resume()
```

## 実行結果

```command:実行結果
-------------
Marius Hills and a Hole in the Moon
-------------
Could humans live beneath the surface of the Moon? This intriguing possibility was bolstered in 2009 when Japan's Moon-orbiting SELENE spacecraft imaged a curious hole beneath the Marius Hills region on the Moon, possibly a skylight to an underground lava tube. Follow-up observations by NASA's Lunar Reconnaissance Orbiter (LRO) indicated that the Marius Hills Hole (MHH) visually extends down nearly 100 meters and is several hundred meters wide.  Most recently, ground penetrating radar data from SELENE has been re-analyzed to reveal a series of intriguing second echoes -- indicators that the extensive lava tubes exist under Marius Hills might extend down even kilometers and be large enough to house cities.  Such tubes could shelter a future Moon colony from large temperature swings, micro-meteor impacts, and harmful solar radiation.  Potentially, underground lava tubes might even be sealed to contain breathable air.  These lava tubes likely formed when lunar volcanos were active billions of years ago. Pictured, the surface of Marius Hills region was captured in the 1960s by NASA's Lunar Orbiter 2 mission, while an inset image of the MHH is shown from NASA's continuing LRO.  Several volcanic domes are visible, while Marius Crater is visible on the upper right.
-------------
https://apod.nasa.gov/apod/image/1710/MariusHills_LO2LRO_1673.jpg
-------------
```

## ポイント
Swift 4.0から採用された **Codable** を使ってAPIを解析


詳細は、下記リンクを参照してください。

[Encoding and Decoding Custom Types - Apple](https://developer.apple.com/documentation/foundation/archives_and_serialization/encoding_and_decoding_custom_types)