swiftmacosswiftuionappearplaygrounds

Is there a substitute for onAppear?


I am a novice at SwiftUI and I am playing around with Text-To-Speech functions. I have gotten it to work, but I now want the app to automatically speak a string when opened.

I have set it up like so:

import SwiftUI
import AVFoundation

struct ContentView: View {

    let synth = AVSpeechSynthesizer()    
    let myUtterance = AVSpeechUtterance(string: "Welcome, User!")
    
    var body: some View {
        onAppear(perform: {
            synth.speak(myUtterance)
        })

        HStack {
            Image(systemName: "map")
                .imageScale(.large)
                .foregroundColor(.teal)
            Text("Welcome to CampusAI!")
                .font(.title3)
            Image(systemName: "map")
                .imageScale(.large)
                .foregroundColor(.teal)
        }   
    }
}


However, the program returns an 'unknown error' and will not start preview. This issue disappears - and the app will run - when i delete the onAppear part. Is there any way to fix this error and get my app running?


Solution

  • onAppear is ViewModifier it has to be attached to a view with dot notation.

    struct ContentView: View {
    
        let synth = AVSpeechSynthesizer()    
        let myUtterance = AVSpeechUtterance(string: "Welcome, User!")
        
        var body: some View {
    
    
            HStack {
                Image(systemName: "map")
                    .imageScale(.large)
                    .foregroundColor(.teal)
                Text("Welcome to CampusAI!")
                    .font(.title3)
                Image(systemName: "map")
                    .imageScale(.large)
                    .foregroundColor(.teal)
            }.onAppear(perform: { // <<--- HERE
                synth.speak(myUtterance)
            })   
        }
    }