swiftobjective-cuiviewcontrollerxcode-storyboardavkit

Objective-C equivalent of simple Swift video player does not show video


I'm creating a simple storyboard that plays an mp4 video. This works as expected in Swift, but when I try to do the exact same thing in Objective-C nothing happens. Can anyone see if I'm doing anything wrong in the Objective-C code converted from Swift?

Notes:

Code:

// Swift implementation
import UIKit
import AVKit
import AVFoundation
class ViewController: UIViewController {
  override func viewDidLoad() {
    super.viewDidLoad()
    let path = Bundle.main.path(forResource: "anim2", ofType:"mp4");
    let url = NSURL(fileURLWithPath: path!) as URL;
    let player = AVPlayer(url: url);
    let playerLayer = AVPlayerLayer(player: player);
    playerLayer.frame = self.view.bounds;
    self.view.layer.addSublayer(playerLayer);
    player.play();
  }
}

// Objective-C implementation
#import "ViewController.h"
#import <AVKit/AVKit.h>
#import <AVFoundation/AVFoundation.h>
@interface ViewController ()
@end
@implementation ViewController
- (void)viewDidLoad {
  [super viewDidLoad];
  NSString* path = [[NSBundle mainBundle] pathForResource:@"anim2" ofType:@"mp4"];
  NSURL* url = [NSURL fileURLWithPath:path isDirectory:false];
  AVPlayer* player = [[AVPlayer alloc] initWithURL:url];
  AVPlayerLayer* playerLayer = [[AVPlayerLayer alloc] initWithLayer:player];
  playerLayer.frame = self.view.bounds;
  [self.view.layer addSublayer:playerLayer];
  [player play];
}
@end

Solution

  • This line is not the same:

    AVPlayerLayer* playerLayer = [[AVPlayerLayer alloc] initWithLayer:player];
    

    That tries to treat an AVPlayer as a CALayer, which is going to quietly fail. You don't get a warning here because initWithLayer: takes id as its type.

    What you meant was:

    AVPlayerLayer* playerLayer = [AVPlayerLayer playerLayerWithPlayer: player];