Pass Data from Swift to SwifUI

I developed a framework in Swift and designed a screen/view via SwiftUI.

SwiftUI view will be presented on top of the Window by the class written in Swift.

Now I need to pass the data from the Swift class to SwiftUI.

Could one any help to know the best practice to pass the data to show the progress from Swift class to Swift UI.


func A () {}

func B () {
// score will get updated frequently
score  = ....
ScorePresenter().presentScoreUI()
}
}

import SwiftUI

struct ScorePresenter: {
func presentScoreUI() {
let hostController = UIHostingController(rootView: ScoreUI())
hostController = .overCurrentContext
topViewController()!.present(hostController, animated: true, completion: nil)
}
}

struct ScoreUI: View {
var score = 1
Text(score).foregroundColor(.green)
}


When ever score changes in Score class ScoreUI must be updated accordingly.

Did you try to use notifications, sent by Swift code and received by SwiftUI part ?

Details here for notifications in SwiftUI:

https://stackoverflow.com/questions/59552487/swiftui-with-notificationcenter-publishers

This is how I ended up.


    var score = "1"

    func A () {}

    

    func B () {

        // score will get updated frequently

        let scoreModal =  ScoreUIViewModel()

        let scoreUI: ScoreUI = ScoreUI(showModal: .constant(true), scoreUIViewModel: scoreModal)

        DispatchQueue.main.async {

            scoreUI.displayScoreUI()

        }

       // score getting updated from another class

        scoreModal.score = score

// score getting updated from another class
        score  = "2"

        scoreModal.score = "2"

// score getting updated from another class
        score  = "3"

        scoreModal.score = "3"

// score getting updated from another class      
  score  = "4"

        scoreModal.score = "4"

     .......
        

    }

}







import SwiftUI



class ScoreUIViewModel: Observable {

    @Published score: String

}

struct ScoreUI: View {

    @State var scoreUIViewModel: ScoreUIViewModel

    func displayScoreUI() {

        let hostController = UIHostingController(rootView: ScoreUI())

        hostController = .overCurrentContext

        topViewController()!.present(hostController, animated: true, completion: nil)

    }.environmentObject(scoreUIViewModel)

    

}



struct ScoreText: View {

    @EnvironmentObject var scoreUIViewModel: ScoreUIViewModel

    Text(score).foregroundColor(.green)
}
Pass Data from Swift to SwifUI
 
 
Q