UPGRADE YOUR SKILLS: Learn advanced Swift and SwiftUI on Hacking with Swift+! >>

Passing an "Observed" Bool to a helper class

Forums > SwiftUI

As usual, there is a ton more code to this, I just stripped it down to the current problem. I have a helper class called SchedulingItems. In it, there is a function called peformScheduleUpdate. Something in that function checks the settings of the app and if they do not have locations services turned on, an alert needs to be shown. But you can't show an alert from a class. I need to pass the proper bool to that class, so when it changes, the ContentView see that and shows the alert.

AppDelegate (that creates the Scheduling Items class)

class AppDelegate: UIResponder, UIApplicationDelegate {

    let schedulingItems = SchedulingItems()

    // @State var showAlert = false //  Should it be created here?  How do I pass that to the rest of the app

    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
        return true
    }
  }

Scheduling Items (that changes the Bool)

class SchedulingItems {

    var boolForTestingPurposesOnly = false

    // @Binding var showAlert: Bool 

    func peformScheduleUpdate() {

        if boolForTestingPurposesOnly {
            print("Yeah, everything works.")
        } else {
            print("Oh, no, they need to go to the iPhones settings and change something.")
            print("I need to show an alert, but I can't here.")
            // showAlert = true
        }
    }
}

ContentView (that uses the Bool to show the alert)

struct ContentView: View {

    @State var showAlert = false

    var body: some View {
        Text("Hello, World!")
        .alert(isPresented: $showAlert) {
            Alert(title: Text("Hello SwiftUI!"), message: Text("This is some detail message"), dismissButton: .default(Text("OK")))
        }
    }
}

3      

Hacking with Swift is sponsored by RevenueCat

SPONSORED Take the pain out of configuring and testing your paywalls. RevenueCat's Paywalls allow you to remotely configure your entire paywall view without any code changes or app updates.

Learn more here

Sponsor Hacking with Swift and reach the world's largest Swift community!

Archived topic

This topic has been closed due to inactivity, so you can't reply. Please create a new topic if you need to.

All interactions here are governed by our code of conduct.

 
Unknown user

You are not logged in

Log in or create account
 

Link copied to your pasteboard.