tezvyn:

Play a remote video with AVFoundation

AI-drafted, machine-checkedSource: interviewbeginner
WHAT IT TESTS

Knowing the AVPlayer rendering stack.

OUTLINE

Wrap the URL in AVPlayerItem, feed it to AVPlayer, render with AVPlayerLayer added to the view's layer (or AVPlayerViewController for controls).

WHAT THIS TESTS This checks familiarity with AVFoundation's playback object model and the key insight that AVPlayer manages timing and state but does not render; a layer does.

A GOOD ANSWER COVERS You construct an AVPlayerItem to represent the media you want to play, typically from a URL, optionally through an AVURLAsset for more control over loading. You hand the item to an AVPlayer, the controller object that manages playback state, rate, and seeking, with play() and pause(). Because AVPlayer has no visual representation, you display it with an AVPlayerLayer, a CALayer subclass: create AVPlayerLayer(player:), set its frame to the host view's bounds, choose videoGravity such as resizeAspect, and add it to the view's layer as a sublayer. Alternatively, use AVPlayerViewController, which wraps all of this and provides standard transport controls; you set its player and present or embed it.

COMMON WRONG ANSWERS Believing AVPlayer renders content by itself without a layer. Trying to display video in a UIImageView. Forgetting to update the AVPlayerLayer frame in layoutSubviews so it does not resize. Not observing the item's status before calling play, leading to silent failures on a bad URL.

LIKELY FOLLOW-UPS How to know when playback is ready: KVO on AVPlayerItem.status or AVPlayer.timeControlStatus. How to loop or chain clips with AVQueuePlayer and AVPlayerLooper. How buffering relates to AVPlayerItem.isPlaybackLikelyToKeepUp. Setting AVAudioSession for background audio.

ONE CONCRETE EXAMPLE In a custom view you write let player = AVPlayer(url: remoteURL), then let layer = AVPlayerLayer(player: player), set layer.frame = bounds and layer.videoGravity = .resizeAspect, and call self.layer.addSublayer(layer). In layoutSubviews you keep layer.frame in sync with bounds. Calling player.play() streams and shows the video. If you instead want play, pause, and scrubbing controls for free, you present an AVPlayerViewController with its player set to that AVPlayer.

Read the original → developer.apple.com

Get five bites like this every day.

Tezvyn delivers a daily feed of 60-second tech bites with quizzes to lock in what you learn.