Philip Pegden
Philip Pegden

Reputation: 2164

GCControllerDidConnect notification not received in VisionOS 2.0

I am unable to get VisionOS 2.0 (simulator) to receive the GCControllerDidConnect notification and thus am unable to setup support for a gamepad. However, it works in VisionOS 1.2.

For VisionOS 2.0 I've tried adding:

...but the notification still doesn't fire. It does when the code is run from VisionOS 1.2 simulator, both of which have the Send Game Controller To Device option enabled.

Here is the example code. It's based on the Xcode project template. The only files updated were ImmersiveView.swift and Info.plist, as detailed above:

import SwiftUI
import GameController
import RealityKit
import RealityKitContent

struct ImmersiveView: View {

    var body: some View {
        RealityView { content in
            // Add the initial RealityKit content
            if let immersiveContentEntity = try? await Entity(named: "Immersive", in: realityKitContentBundle) {
                content.add(immersiveContentEntity)
            }
            NotificationCenter.default.addObserver(
                forName: NSNotification.Name.GCControllerDidConnect,
                object: nil, queue: nil) { _ in
                    print("Handling GCControllerDidConnect notification")
                }
            
        }
        .modify {
            if #available(visionOS 2.0, *) {
                $0.handlesGameControllerEvents(matching: .gamepad)
            } else {
                $0
            }
        }
    }
}

extension View {
    func modify<T: View>(@ViewBuilder _ modifier: (Self) -> T) -> some View {
        return modifier(self)
    }
}

Upvotes: 0

Views: 79

Answers (1)

lorem ipsum
lorem ipsum

Reputation: 29614

Try using onReceive

.onReceive(NotificationCenter
    .default
    .publisher(
        for: .GCControllerDidConnect,
        object: nil),
           perform: { _ in
                print("Handling GCControllerDidConnect notification")
            }
)

Your notification is just floating there right now it doesn't really have an owner.

Upvotes: 0

Related Questions