Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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)
        })   
    }
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading