I need to use external screen do lyrics projection (I develop app for chords & lyrics). Everything works fine until I move app to background and back to foreground. View on external screen is not updating (on appear it shows correct number and then does not update).
You can see the problem here: https://media.justchords.online/SwiftUIExtScreenProblem.mov
Settings in Info.plist: EnableMultipleWindows = YES SceneConfiguration / External Display Session Role Non-Interactive: Configuration Name = External Delegate Class Name = $(PRODUCT_NAME).ExternalSceneDelegate
Test view for external screen:
struct ExternalScreenTestView: View { @ObservedObject var counter = TestCounter.shared var body: some View { Text(counter.count.description) .font(.system(size: 50)) } } class TestCounter: ObservableObject { private var timer: Timer? @Published var count = 1 static var shared:TestCounter = TestCounter() init() { self.timer = Timer.scheduledTimer(withTimeInterval: 1, repeats: true) { _ in self.count += 1 } } } My SceneDelegate:
final class ExternalSceneDelegate: UIResponder, UIWindowSceneDelegate { var window: UIWindow? var controller: UIHostingController<ExternalScreenTestView>? func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) { guard let scene = scene as? UIWindowScene else { return } let content = ExternalScreenTestView() window = UIWindow(windowScene: scene) controller = UIHostingController(rootView: content) window?.rootViewController = controller window?.isHidden = false } }
Views are structs they have no lifetime so you can't useDispatchQueue.main.asyncbecause the struct is gone by the time the closure is called. You either need to use.taskthat has an internal object, or make your own@StateObjector just useTimelineViewthat already implements an object as lorem already said.