Search code examples
swiftmpmovieplayercontroller

Playing a video without stopping (Swift)


I'm trying to play 10-20 second videos on my swift App but sometimes because of slow internet it stops and doesn't load again until I pause it and play. So what I want to do is before streaming, download the full video so it doesn't stop in middle again. This is the code I'm using

moviePlayer = MPMoviePlayerController(contentURL: url)
        moviePlayer.movieSourceType = MPMovieSourceType.File
        moviePlayer.controlStyle = MPMovieControlStyle.None
        moviePlayer.view.backgroundColor = UIColor.blueColor()
        moviePlayer.scalingMode = MPMovieScalingMode.AspectFit
        moviePlayer.repeatMode = MPMovieRepeatMode.None;
        moviePlayer.allowsAirPlay = false
        moviePlayer.shouldAutoplay = false
        moviePlayer.backgroundView.backgroundColor = UIColor.whiteColor()
        moviePlayer.view.frame = self.bounds
        self.addSubview(moviePlayer.view)

Solution

  • This is what I did, added an observer to find if downloading

    NSNotificationCenter.defaultCenter().addObserver(self, selector: "videoStopped:", name: MPMoviePlayerLoadStateDidChangeNotification, object: moviePlayer)
    

    handle the playing in videoStopped Function using moviePlayer.currentPlaybackTime and moviePlayer.playableDuration