2
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

【Swift】SwityJSONを使用して占いAPIのJSONデータから簡単に情報を取得する

Posted at

占いを無料で提供しているAPIがあったので、Swiftで呼び出そうと思ったらJSONの子要素の名前が日付(2021/01/01)のような形式で戸惑ってしまった。
SwiftyJSONを使用することで解決出来そうなので試してみた。

開発環境

Xcode 12.3
SwiftyJSON 5.0.0

SwiftyJSONを使用し、APIから情報を取得

例として、2021/01/05の牡羊座の恋愛運(love)を取得

import UIKit
import SwiftyJSON

class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        getHoroscopeDate()
    }

    private func getHoroscopeDate() {
        
        guard let url = URL(string: "http://api.jugemkey.jp/api/horoscope/free/2021/01/03") else { return }
        let task = URLSession.shared.dataTask(with: url) { (data, response, error) in
            if let error = error {
                print("error", error)
                return
            }
            guard let data = data else {
                print("Data情報の取得に失敗しました")
                return
            }
            do {
                let json = try? JSON(data: data)
                if let json = json {
                    let love = json["horoscope"]["2021/01/05"][0]["love"]
                    print(love)
                }
            }
        }
        task.resume()
    }
}

API用に構造体を作成する必要もなく、かなり簡単に希望の情報が取得出来ました。

JSONデータ

取得結果(2021/01/05)

{
    "horoscope": {
        "2021/01/05": [
        {
        "content": "図書館で過ごす時間は、あなたの想像力を高めてくれます。悩んでいることがあるなら、好きな作家の本を読んでみて。",
        "item": "鍋料理",
        "money": 4,
        "total": 3,
        "job": 3,
        "color": "グリーン",
        "day": 5,
        "love": 3,
        "rank": 7,
        "sign": "牡羊座"
        },

.......以下11星座分が続きます

        ]
    }
}

参考

SwiftyJSON

使用したAPI

Web ad Fortune 無料API
利用の条件があり、商用利用する場合は有料版を使うようにしてください。

まとめ

SwiftyJSONを使用したら本当に簡単にJSONデータから情報を取得できた。
とても便利なライブラリなので理解をもっと深めたい。

2
4
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?