There was an API that provided fortune-telling for free, so when I tried to call it with Swift, the name of the JSON child element was confused in a format like date (2021/01/01). It seems that it can be solved by using Swifty JSON, so I tried it.
Xcode 12.3 SwiftyJSON 5.0.0
As an example, get the Aries love luck on January 05, 2021
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("Failed to get Data information")
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()
}
}
I was able to get the desired information fairly easily without having to create a structure for the API.
Acquisition result (2021/01/05)
{
"horoscope": {
"2021/01/05": [
{
"content": "The time you spend in the library will enhance your imagination. If you're having trouble, read a book by your favorite author.",
"item": "casserole",
"money": 4,
"total": 3,
"job": 3,
"color": "green",
"day": 5,
"love": 3,
"rank": 7,
"sign": "Aries"
},
.......Below are 11 constellations
]
}
}
Web ad Fortune Free API There are conditions of use, so please use the paid version for commercial use.
Using Swifty JSON made it really easy to get information from JSON data. It's a very useful library, so I want to deepen my understanding.
Recommended Posts