Search code examples
iosswiftsprite-kitavplayerskscene

Detect when the local video ended and move to another Scene


How to detect that the local video ended and move to another Scene?

this is the code :

import SpriteKit
import GameplayKit
import AVKit
import AVFoundation

class intro: SKScene {

  override func didMove(to view: SKView) {
      let urlStr = Bundle.main.path(forResource: "Opening", ofType: "mp4")
      let url = NSURL(fileURLWithPath: urlStr!)

      let player = AVPlayer(url: url as URL)

      let videoNode = SKVideoNode(avPlayer: player)
      videoNode.position = CGPoint(x: 0, y: 0)
      videoNode.size = CGSize(width: self.frame.width, height: self.frame.height)
      videoNode.zPosition = 1

      addChild(videoNode)
      videoNode.play()
  }

  override func update(_ currentTime: TimeInterval) {
      // Called before each frame is rendered
  }
}

i need to know how to move to another scene once the video ends . thanks.


Solution

  • You can fire notification like this:

      NotificationCenter.default.addObserver(self, selector: #selector(self.playerDidFinishPlaying),
                                                   name: NSNotification.Name.AVPlayerItemDidPlayToEndTime,
                                                   object: self.player!.currentItem)
    
    
    
     @objc func playerDidFinishPlaying(){
        print("Player finished")
    }