Created
March 2, 2018 20:14
-
-
Save ManjitBedi/32fab473d67ce281b667cdd2bc66dc3d to your computer and use it in GitHub Desktop.
Loop video using key value observer in Swift 3
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| var introPlayer: AVPlayer? | |
| var introPlayerLayer: AVPlayerLayer? | |
| fileprivate var playerObserver: Any? | |
| let keyPathToObserve:String = "isReadyForDisplay" | |
| override func viewDidLayoutSubviews() { | |
| super.viewDidLayoutSubviews() | |
| if introPlayer == nil { | |
| playVideo() | |
| } | |
| } | |
| func playVideo() { | |
| let path = Bundle.main.path(forResource: "videoLoop", ofType: "mp4") | |
| let url = NSURL.fileURL(withPath: path!) | |
| introPlayer = AVPlayer(url: url) | |
| if let introPlayer = introPlayer { | |
| introPlayer.allowsExternalPlayback = false | |
| introPlayerLayer = AVPlayerLayer(player: introPlayer) | |
| introPlayerLayer?.backgroundColor = UIColor.clear.cgColor | |
| introPlayerLayer?.videoGravity = AVLayerVideoGravityResizeAspectFill | |
| self.view.layer.insertSublayer(introPlayerLayer!, at: 0) | |
| introPlayerLayer?.frame = self.view.bounds | |
| introPlayer.rate = 1 | |
| playerObserver = NotificationCenter.default.addObserver(forName: NSNotification.Name.AVPlayerItemDidPlayToEndTime, object: introPlayer.currentItem, queue: nil) { notification in | |
| self.resetPlayer() | |
| } | |
| // register for KVO change of the ready to play property | |
| // Note: need to keep a reference to the player layer for this to compile (?) | |
| addObserver(self, forKeyPath: #keyPath(introPlayerLayer.isReadyForDisplay), options: [.old, .new], context: nil) | |
| } | |
| } | |
| func resetPlayer() { | |
| introPlayer?.seek(to: kCMTimeZero) | |
| introPlayer?.play() | |
| } | |
| override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) { | |
| if keyPath == #keyPath(introPlayerLayer.isReadyForDisplay) { | |
| self.backgroundImage.isHidden = true | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment