I want to create a vocabulary app with pronounce. Because I am a fresh to swiftUI and try to self-learning, so I am try to watch online coding and modify. I have create a local Json file with a "LearnMode" view, and also I take a reference of text to speech coding example online to made a "soundicon" view, but I have no idea that how I can make them work together. Currently I make each " trumpet“ icon with an "apple" pronounce, I don't know how I can attached each of the Json word to pronounce, I think the way are pretty easy, but I cannot figure out. Here are 2 swiftUI file coding, many thanks for your help:
//LearnMode.swift
import SwiftUI
struct Model1: Codable,Identifiable{
enum CodingKeys: CodingKey{
case word
case interpretation
}
var id = UUID()
var word,interpretation:String
}
class Json1: ObservableObject{
@published var json = Model1
init(){
load()
}
func load(){
let path = Bundle.main.path(forResource:"data",ofType:"json")
let url = URL(fileURLWithPath: path!)
URLSession.shared.dataTask(with: url){(data,response,error) in
do{
if let data = data {
let json = try JSONDecoder().decode([Model1].self, from:data)
DispatchQueue.main.sync{
self.json = json
}
}else{
print("No data")
}
} catch {
print(error)
}
}.resume()
}
}
struct LearnMode: View {
@ObservedObject var datas = Json1()
var body: some View {
NavigationView{ZStack{
List(datas.json){item in
HStack{
Text(item.word)
.font(.system(size: 16))
Spacer()
Text(item.interpretation)
.multilineTextAlignment(.leading)
.frame(width: 50, height: 60)
.font(.system(size: 12))
.foregroundColor(Color.gray)
SoundIcon()
}
}
}
.navigationTitle("IELTS")
.navigationBarTitleDisplayMode(.inline)
}
}
}
struct LearnMode_Previews: PreviewProvider {
static var previews: some View {
LearnMode()
}
}
// SoundIcon.swift
import SwiftUI
import AVFoundation
struct SoundIcon: View {
var body: some View {
Button(){
let utterance = AVSpeechUtterance(string: "apple")
utterance.voice = AVSpeechSynthesisVoice(language:"en-US")
utterance.rate = 0.5
let synthesizer = AVSpeechSynthesizer()
synthesizer.speak(utterance)
}label:{
Image(systemName: "speaker.wave.1")
}
}
}
struct SoundIcon_Previews: PreviewProvider {
static var previews: some View {
SoundIcon()
}
}