My app (Swift 3, with a UIStoryboard) shows a list of episodes from a show. Whenever the user clicks on an episode from the table, he/she gets a detail view which shows (top to bottom): 
Depending on the user type, instead of showing the episode's image, we would like to have a video player so people who are subscribed can just start watching the video (unsubscribed users would just see the image).
Based on the subscribed status of our users, a video player should be playing the content (subscribed) or showing an image (unsubscribed).
Is there a way to dynamically remove the image and replace it with the video player in the exact same spot and dimensions? And if so, what would happen with the Auto Layout contraints currently applied to the image?
Place a UIView on top of the UIImageView in storyboard. Align it to all 4 edges of UIImageView. And then hide and show them according to requirement by setting isHidden property.
Then, Insert the AVPlayer in the UIView through code.
The following solution works for both UIStoryboard and UI in code.
UIView of preferred size onto the canvas, add your auto layout constraints and create an outlet (called "containerView")URL or file, initialize an AVPlayerLayer instance with the player and add the layer to the containerView's layer hierarchyUIImageView on top of the container viewimport UIKit
import AVFoundation
class ViewController: UIViewController {
    // MARK: - Properties
    @IBOutlet var containerView: UIView!
    private var imageView: UIImageView!
    private var isUserSubscribed = true
    // MARK: - Lifecycle
    override func viewDidLoad() {
        super.viewDidLoad()
        // Video
        let url = URL(string: "https://content.jwplatform.com/manifests/vM7nH0Kl.m3u8")!
        let avPlayer = AVPlayer(playerItem: AVPlayerItem(url: url))
        let avPlayerLayer = AVPlayerLayer(player: avPlayer)
        avPlayerLayer.frame = containerView.bounds
        containerView.layer.insertSublayer(avPlayerLayer, at: 0)
        // Image
        imageView = UIImageView(image: UIImage(named: "someImage"))
        imageView.frame = containerView.frame
        containerView.addSubview(imageView)
        // Condition
        if isUserSubscribed {
            imageView.isHidden = true
            avPlayer.play()
        } else {
            imageView.isHidden = false
        }
    }
}

With this approach you need to add your own playback controls, which basically boils down to adding buttons with actions, triggering AVPlayer.play(), AVPlayer.stop() etc.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With