Hello everyone,
I have a bit of an issue that I expected to be fairly simple to solve. I have scoured the internet but have run out of solutions to test out.
Task:
I am trying to setup a very simple Dictionary API call from my iOS application with this link: https://api.dictionaryapi.dev/api/v2/entries/en/hello
And show the result of it in a basic View (using Text{}) with SwiftUI.
Problem:
The code compiles, but my ContentView is blank.
Debugging so far:
I followed a tutorial on setting up JSON parsing with the "Codable" protocol and was able to successfully set it up using a link that was a Movie API database. Upon further investigation on why the MovieAPI results were working and the DictionaryAPI results weren't, I noticed the the MovieAPI response was a JSONObject and the DictionaryAPI response was a JSONArray
which starts with [ ]
After more googling I was sent to the solution to utilize something like this:
try! JSONDecoder().decode([DictionaryWord].self, from: jsonData)
But it also did not work and my view is still blank. I will be putting the code below as well for further reference. Thank you
import SwiftUI
struct ContentView: View {
@State private var results = [DictionaryWord]()
var body: some View {
VStack{
Text("API Example iOS Application")
List(results, id: \.word) { item in
VStack(alignment: .leading) {
Text(item.word)
.font(.headline)
Text(item.phonetic)
}
}
.task {
await loadData()
}
}
}
let freeDictionaryURL = "https://api.dictionaryapi.dev/api/v2/entries/en/hello"
func loadData() async {
guard let url = URL(string: freeDictionaryURL) else {
print("Invalid URL")
return
}
do {
let (data, _) = try await URLSession.shared.data(from: url)
if let decoded: [WelcomeElement] = try? JSONDecoder().decode([DictionaryWord].self, from: data) {
results = decoded
}
} catch {
print("Invalid data")
}
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
// MARK: - WelcomeElement
struct DictionaryWord: Codable {
var word, phonetic: String
var phonetics: [Phonetic]
var origin: String
var meanings: [Meaning]
}
// MARK: - Meaning
struct Meaning: Codable {
var partOfSpeech: String
var definitions: [Definition]
}
// MARK: - Definition
struct Definition: Codable {
var definition, example: String
var synonyms, antonyms: [String?]
}
// MARK: - Phonetic
struct Phonetic: Codable {
var text: String
var audio: String?
}