简体   繁体   中英

AVPlayer not showing video in iOS7, working fine on iOS8 and iOS9

This is my code,

@interface ViewController ()
{
    AVPlayer *avPlayer;
}
@end

- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
    UIView *containerView = [[UIView alloc] initWithFrame:self.view.frame];
    NSString *filepath = [[NSBundle mainBundle] pathForResource:@"TestVideo" ofType:@"mp4"];
    AVAsset *asset = [AVAsset assetWithURL:[NSURL fileURLWithPath:filepath]];
    AVPlayerItem *playerItem = [[AVPlayerItem alloc] initWithAsset:asset];
    avPlayer = [AVPlayer playerWithPlayerItem:playerItem];
    AVPlayerLayer *avPlayerLayer = [AVPlayerLayer playerLayerWithPlayer:avPlayer];

    avPlayerLayer.frame = self.view.frame;
    [containerView.layer addSublayer:avPlayerLayer];
    [self.view addSubview:containerView];
    [avPlayer play];
}

That really shouldn't work on any iOS version as

AVPlayer *avPlayer = [AVPlayer playerWithPlayerItem:playerItem];

is going out of scope and being deallocated at the end of viewDidAppear .

You should assign the AVPlayer to a class member variable, to stop this happening.

Otherwise there may be a problem with the video file.

Your AVPlayer item needs a strong reference as it sets to nil automatically

Please change

@interface ViewController ()

{
    AVPlayer *avPlayer;
}
@end

to this

@interface ViewController ()  
@property (strong, nonatomic) AVPlayer *avPlayer;
@end

and change all avPlayer reference to self.avPlayer I hope this helps.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM