rive-app/rive-ios

State machine delegate not working

Closed this issue · 2 comments

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)

  • Device: [iOS Simulator, iPhone 13 Pro]
  • iOS version [>= iOS 15]

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

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

@zplata that works! thank you