rive-app / rive-ios

iOS runtime for Rive
MIT License
468 stars 53 forks source link

State machine delegate not working #245

Closed harunagic closed 1 year ago

harunagic commented 1 year ago

Description

I am trying to listen for state changes in rive file, for example: wanna trigger some action when state i changed or animation is finished.

Here is my code snippet so you can check if I am doing something wrong or there is an issue

Provide a Repro

class StairsRiveViewModel : RiveViewModel {

    private let unlockDuration: Int = 4000
    var startModuleCallback: ((String) -> Void) = { _ in }

    init() {
        super.init(fileName: "stairs", stateMachineName: "stairways-state")
    }

    override func setView(_ view: RiveView) {
        super.setView(view)
        view.playerDelegate = self
        view.stateMachineDelegate = self
        print("Delegates attached!")
    }

    func view(_ startModuleCallback: @escaping ((String) -> Void)) -> some View {
        self.startModuleCallback = startModuleCallback
        return super.view()
    }

    override func player(playedWithModel riveModel: RiveModel?) {
        if let animationName = riveModel?.animation?.name() {
            print("PLAY: \(animationName)")
        }
    }

    override func player(stoppedWithModel riveModel: RiveModel?) {
        if let stateName = riveModel?.stateMachine?.name() {
            print("STOP: \(stateName)")
            navigateToQuestScreen(stateName: stateName)
        }
    }

    func stateMachine(_ stateMachine: RiveStateMachineInstance, didChangeState stateName: String) {
        print("State changed!")
    }

    private func navigateToQuestScreen(stateName: String) {
        if (stateName.contains("unlock")) {
            let doorNumber = stateName[4..<5]
            startModuleCallback(doorNumber)
        }
    }
}

Device & Versions (please complete the following information)

zplata commented 1 year ago

Hey @harunagic - can you try changing func stateMachine() to @objc func stateMachine()?

It's incorrect in the docs - so we'll fix that up

harunagic commented 1 year ago

@zplata that works! thank you