Receive notifications for focus changes between apps on Split View when using SwiftUI

Viewed 199

What should I observe to receive notifications in a View of focus changes on an app, or scene, displayed in an iPaOS Split View?

I'm trying to update some data, for the View, as described here, when the user gives focus back to the app.

Thanks.

1 Answers

Here is a solution that updates pasteDisabled whenever a UIPasteboard.changedNotification is received or a scenePhase is changed:

struct ContentView: View {
    @Environment(\.scenePhase) private var scenePhase
    @State private var pasteDisabled = false

    var body: some View {
        Text("Some Text")
            .contextMenu {
                Button(action: {}) {
                    Text("Paste")
                    Image(systemName: "doc.on.clipboard")
                }
                .disabled(pasteDisabled)
            }
            .onReceive(NotificationCenter.default.publisher(for: UIPasteboard.changedNotification)) { _ in
                updatePasteDisabled()
            }
            .onChange(of: scenePhase) { _ in
                updatePasteDisabled()
            }
    }

    func updatePasteDisabled() {
        pasteDisabled = !UIPasteboard.general.contains(pasteboardTypes: [aPAsteBoardType])
    }
}
Related