Taimur Ajmal Taimur Ajmal - 4 months ago 27
iOS Question

iOS Airplay - "Playing on your TV"

I have displayed the airplay button using this code

var airplayButton: UIBarButtonItem!
let airView: MPVolumeView = MPVolumeView()
airView.showsRouteButton = true
airView.showsVolumeSlider = false
airView.sizeToFit()
airView.tintColor = UIColor.blackColor()

airplayButton = UIBarButtonItem(customView: airView)
airplayButton.tintColor = UIColor.whiteColor()


Now, I want to display a screen. Is there any default method in iOS Airplay framework to display it. Or I have to design screen myself. Also, there are no delegates to verify when the device is connected and movie start streaming on AppleTV through iOS Device. I only have a variable to check i.e externalPlaybackActive

The issue is If I use the variable it wouldn't be efficient solution as I have airplay can be connected from Control during playback. I don't want to run a timer to check after each second if the movie is streaming on AppleTV. Any better ideas ?


This video is playing on "Apple TV"


Like this image

Answer

This is how I implemented it. It works like a charm !

//Airplay constants

private var observerContextAirplay = 1

private var propertyToObserveAirplay = "externalPlaybackActive"

 // MARK: AirPlay Key-value Observing

    func startObservingForAirPlayStatusChanges()
    {
        self.player.moviePlayer.addObserver(self, forKeyPath: propertyToObserveAirplay, options: .New, context: &observerContextAirplay)
    }

    func stopObservingForAirPlayStatusChanges()
    {
        self.player.moviePlayer.removeObserver(self, forKeyPath: propertyToObserveAirplay)
    }

    override func observeValueForKeyPath(keyPath: String?, ofObject object: AnyObject?, change: [String : AnyObject]?, context: UnsafeMutablePointer<Void>) {
        if context == &observerContextAirplay {
            if self.player.moviePlayer.externalPlaybackActive == true
            {                    
                self.setUpAirPlayView()
            }
            else if self.player.moviePlayer.externalPlaybackActive == false
            {
                self.resetPlayerView()
            }

        }
        else {
            super.observeValueForKeyPath(keyPath, ofObject: object, change: change, context: context)
        }
    }
Comments