iosswiftuicontainerviewsegmentedcontrol

Video autoplayed - ContainerView - Switching between views - Swift 3


I have an HMSegmentedControl used for switching between segments. I used container view to switch between these segments, which works fine, but one of my tabs have a video that is autoplayed on viewDidAppear. So my problem is that as container view loads everything prior and shows views depending on isHidden = false, my video starts playing even if that segment isn't selected. How can I go about this situation?

This is my code on segmentedControlValueChanged event

print("selected index \(segmentedControl.selectedSegmentIndex)")

    switch segmentedControl.selectedSegmentIndex {
    case 0:
        liveContainer.isHidden = true
    case 1:
        liveContainer.isHidden = true
    case 2:
        liveContainer.isHidden = false
    default:
        break
    }

Solution

  • You can use NSNotificationCenter to send notification to the view controller that contains the video when it is shown/hidden to play/stop the video. This can be done in the container view segment selection. So, you can remove autoplay from viewDidAppear and add it to the method called when the notification is sent.

    For example, in your segmentedControlValueChanged event, you can write:

    switch segmentedControl.selectedSegmentIndex {
    case 0:
        liveContainer.isHidden = true
        NotificationCenter.default.post(name: Notification.Name("StopVideo"), object: nil)
    case 1:
        liveContainer.isHidden = true
        NotificationCenter.default.post(name: Notification.Name("StopVideo"), object: nil)
    case 2:
        liveContainer.isHidden = false
        NotificationCenter.default.post(name: Notification.Name("PlayVideo"), object: nil)
    default:
        break
    }
    

    and in your video ViewController, you can have two methods: one for playing video:

    func playVideo() {
      //play video here
    }
    

    and another for stopping it:

    func stopVideo() {
      //stop video here
    }
    

    and in your video ViewController's viewDidLoad method, you can add observers:

    NotificationCenter.default.addObserver(self, selector: #selector(playVideo), name: "PlayVideo", object: nil)
    NotificationCenter.default.addObserver(self, selector: #selector(stopVideo), name: "StopVideo", object: nil)