搞透AVPlayerViewController,摆出我想要的姿势

百家 作者:iOS开发 2019-01-08 12:56:02

Linux编程
点击右侧关注,免费入门到精通!


作者丨红发_KVO

https://www.jianshu.com/p/63e038c73e7d


有那么一些时候,我们只需要简单的播放一些小视频,本地的或者网上的资源,不需要各种炫酷的效果,不需要自己各种控制,只是想安安静静的播放完,退出!网上各种开源的封装的AVPlayer的开源库,各有千秋,但是集成进来有感觉动静太大了,大把大把的控件和控制代理等等,头都大了!对于我这种菜逼,慌得一批~~所以我就在系统提供的AVPlayerViewController动起了手脚!


AVPlayerViewController的最简单使用


#import "ViewController.h"
#import 

@interface ViewController ()
@property (nonatomicstrongNSString *videoUrl;
@property (nonatomicstrong)AVPlayerViewController *playerVC;
@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
//    self.videoUrl =  [[NSBundle mainBundle] pathForResource:@"guideMovie1" ofType:@"mov"];
    self.videoUrl = @"http://clips.vorwaerts-gmbh.de/big_buck_bunny.mp4";
    /*
     因为是 http 的链接,所以要去 info.plist里面设置
     App Transport Security Settings
     Allow Arbitrary Loads  = YES
     */

    self.playerVC = [[AVPlayerViewController alloc] init];
    self.playerVC.player = [AVPlayer playerWithURL:[self.videoUrl hasPrefix:@"http"] ? [NSURL URLWithString:self.videoUrl]:[NSURL fileURLWithPath:self.videoUrl]];
    self.playerVC.view.frame = self.view.bounds;
    self.playerVC.showsPlaybackControls = YES;
//self.playerVC.entersFullScreenWhenPlaybackBegins = YES;//开启这个播放的时候支持(全屏)横竖屏哦
//self.playerVC.exitsFullScreenWhenPlaybackEnds = YES;//开启这个所有 item 播放完毕可以退出全屏
    [self.view addSubview:self.playerVC.view];

    if (self.playerVC.readyForDisplay) {
        [self.playerVC.player play];
    }
}
@end


就是这么简单,我们就可以播放网络或者本地视频啦,简洁大气上档次,还是暗黑风格哦,如果项目开启了屏幕方向,自动支持横竖屏切换,美滋滋!上两张图来占占篇幅哈!!



简单播放竖屏界面



简单播放横屏界面


当是,但是!我们有没有发现,它没有退出按钮,这叫我如何退出呢!这怎么难倒我,加个导航控制器嵌套,so easy~~这时候你又会发现,播放界面的按钮被盖住了(肯定有人会说,进来的时候设置导航栏隐藏就好啦,然后播放完显示导航栏不就好了。。。)接着往下看



拉伸和音量按钮被遮挡了


那么我们来监听播放状态来控制导航栏的显示和隐藏吧!


我们在viewDidload里面增加这个监听,这个 block 监听方式是我学习各位大神写的一个分类,不必自己释放 observer


//添加监听播放状态
    [self HF_addNotificationForName:AVPlayerItemDidPlayToEndTimeNotification block:^(NSNotification *notification) {
        NSLog(@"我播放结束了!");
        [self.navigationController setNavigationBarHidden:NO animated:YES];
    }];

    if (self.playerVC.readyForDisplay) {
        [self.playerVC.player play];
    }


在viewDidAppear里面隐藏导航栏


- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
    [self.navigationController setNavigationBarHidden:YES animated:YES];
}


这样看起来蛮不错的,达到我们预期效果了,就是进去隐藏导航栏,播放结束显示导航栏!


但是这个视频短,如果是很长的怎么办?等到看完才可以退出么,那就太坑爹了,有木有!辣么有没有机制监听到AVPlayerViewController点击播放界面显示工具栏的时候一并显示导航栏呢?这时候就要借助著名的AOP框架Aspects了!在做这件事之前,我们先看下AVPlayerViewController的视图层级和手势数组了!

首先看下面一张图,好好利用视图层级分析器,可以看透很多东西的实现原理哦!



而下面这张图是我们需要监听的音量控制的层级图



从上图,我们可以知道单击和双击手势是添加到了AVPlayerViewControllerContentView上,那我们怎么拦截它做事情呢?接下来看我的:


#import "ViewController.h"
#import 
#import "NSObject+BlockObserver.h"
#import 

@interface ViewController ()
@property (nonatomicstrongNSString *videoUrl;
@property (nonatomicstrong)AVPlayerViewController *playerVC;

//增加两个属性先
//记录音量控制的父控件,控制它隐藏显示的 view
@property (nonatomicweak)UIView *volumeSuperView;
//记录我们 hook 的对象信息
@property (nonatomicstrong)idhookAVPlaySingleTap;
@end


先增加两个属性,用来记录我们需要操作的 view 和 hook 的对象信息!然后在viewDidload里面增加以下代码:


//首先获取我们的手势真正的执行类 UIGestureRecognizerTarget
//然后手势触发的方法 selector 为:_sendActionWithGestureRecognizer:
Class UIGestureRecognizerTarget = NSClassFromString(@"UIGestureRecognizerTarget");
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wundeclared-selector"
    _hookAVPlaySingleTap = [UIGestureRecognizerTarget aspect_hookSelector:@selector(_sendActionWithGestureRecognizer:) withOptions:AspectPositionBefore usingBlock:^(idinfo,UIGestureRecognizer *gest){
        if (gest.numberOfTouches == 1) {
            //AVVolumeButtonControl
            if (!self.volumeSuperView) {
                UIView *view = [gest.view findViewByClassName:@"AVVolumeButtonControl"];
                if (view) {
                    while (view.superview) {
                        view = view.superview;
                        if ([view isKindOfClass:[NSClassFromString(@"AVTouchIgnoringView"class]]) {
                            self.volumeSuperView = view;
                          //  [view addObserver:self forKeyPath:@"hidden" options:NSKeyValueObservingOptionNew|NSKeyValueObservingOptionOld context:nil];
                           [view HF_addObserverForKeyPath:@"hidden" block:^(__weak id object, id oldValue, id newValue) {
                                NSLog(@"newValue ==%@",newValue);
                                BOOL isHidden = [(NSNumber *)newValue boolValue];//记得要转换哦,不然没效果!
                                dispatch_async(dispatch_get_main_queue(), ^{
                                    [self.navigationController setNavigationBarHidden:isHidden animated:YES];
                                });
                        }
                    }
                }
            }
        }

    } error:nil];
#pragma clang diagnostic pop
   if (self.playerVC.readyForDisplay) {
        [self.playerVC.player play];
    }


其中[gest.view findViewByClassName:@"AVVolumeButtonControl"]方法的实现如下:


- (UIView *)findViewByClassName:(NSString *)className
{
    UIView *view;
    if ([NSStringFromClass(self.class) isEqualToString:className]) {
        return self;
    } else {
        for (UIView *child in self.subviews) {
            view = [child findViewByClassName:className];
            if (view != nilbreak;
        }
    }
    return view;
}


设置完,我们需要在 viewDidDisappear里面去释放我们 hook 的对象,防止反复添加 hook 和引用的问题!


- (void)viewDidDisappear:(BOOL)animated
{
    [super viewDidDisappear:animated];
    [self.navigationController setNavigationBarHidden:NO animated:YES];
    [self.hookAVPlaySingleTap remove];
}


完事,我们来验证一下!看看能不能达到我们的预期效果,点击播放界面,实现播放工具栏和导航栏的同步显示隐藏!我们可以预览一下效果:



当然,我能写出来,就说明我验证过啦!不过,在这个基础上,我肯定是想做的更自然一点点,更高大上一点点啦!所以我会自定义一个控件添加到播放控制器的 view 上,同一风格,做到真正的全屏播放,抛弃导航栏!因此,我们需要再添加一个控件属性


//增加一个关闭按钮
@property (nonatomicstrongUIControl *closeControl;

//懒加载
- (UIControl *)closeControl
{
    if (!_closeControl) {
        _closeControl = [[UIControl alloc] init];
        [_closeControl addTarget:self action:@selector(dimissSelf) forControlEvents:UIControlEventTouchUpInside];
        _closeControl.backgroundColor = [UIColor colorWithRed:0.14 green:0.14 blue:0.14 alpha:0.8];
        _closeControl.tintColor = [UIColor colorWithWhite:1 alpha:0.55];
        NSBundle *bundle = [NSBundle bundleForClass:[self class]];
        UIImage *normalImage = [UIImage imageNamed:@"closeAV" inBundle:bundle compatibleWithTraitCollection:nil];
        [_closeControl.layer setContents:(id)normalImage.CGImage];
        _closeControl.layer.contentsGravity = kCAGravityCenter;
        _closeControl.layer.cornerRadius = 17;
        _closeControl.layer.masksToBounds = YES;
    }
    return _closeControl;

}

- (void)dimissSelf
{
    if (self.navigationController.viewControllers.count >1) {
        [self.navigationController popViewControllerAnimated:YES];
    }
    else
    {
        [self dismissViewControllerAnimated:YES completion:nil];
    }

}


然后在viewDidLoad里面修改代码如下,主要是注释掉导航栏显示和隐藏的代码:


- (void)viewDidLoad {
    [super viewDidLoad];
//    self.videoUrl =  [[NSBundle mainBundle] pathForResource:@"guideMovie1" ofType:@"mov"];
    self.videoUrl = @"http://clips.vorwaerts-gmbh.de/big_buck_bunny.mp4";
    /*
     因为是 http 的链接,所以要去 info.plist里面设置
     App Transport Security Settings
     Allow Arbitrary Loads  = YES
     */

    self.playerVC = [[AVPlayerViewController alloc] init];
    self.playerVC.player = [AVPlayer playerWithURL:[self.videoUrl hasPrefix:@"http"] ? [NSURL URLWithString:self.videoUrl]:[NSURL fileURLWithPath:self.videoUrl]];
    self.playerVC.view.frame = self.view.bounds;
    self.playerVC.showsPlaybackControls = YES;
    //self.playerVC.entersFullScreenWhenPlaybackBegins = YES;//开启这个播放的时候支持(全屏)横竖屏哦
    //self.playerVC.exitsFullScreenWhenPlaybackEnds = YES;//开启这个所有 item 播放完毕可以退出全屏
    [self.view addSubview:self.playerVC.view];


    //添加监听播放状态
    [self HF_addNotificationForName:AVPlayerItemDidPlayToEndTimeNotification block:^(NSNotification *notification) {
        NSLog(@"我播放结束了!");
//        [self.navigationController setNavigationBarHidden:NO animated:YES];
    }];


    Class UIGestureRecognizerTarget = NSClassFromString(@"UIGestureRecognizerTarget");
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wundeclared-selector"
    _hookAVPlaySingleTap = [UIGestureRecognizerTarget aspect_hookSelector:@selector(_sendActionWithGestureRecognizer:) withOptions:AspectPositionBefore usingBlock:^(idinfo,UIGestureRecognizer *gest){
        if (gest.numberOfTouches == 1) {
            //AVVolumeButtonControl
            if (!self.volumeSuperView) {
                UIView *view = [gest.view findViewByClassName:@"AVVolumeButtonControl"];
                if (view) {
                    while (view.superview) {
                        view = view.superview;
                        if ([view isKindOfClass:[NSClassFromString(@"AVTouchIgnoringView"class]]) {
                            self.volumeSuperView = view;
//                            [view addObserver:self forKeyPath:@"hidden" options:NSKeyValueObservingOptionNew|NSKeyValueObservingOptionOld context:nil];
                            [view HF_addObserverForKeyPath:@"hidden" block:^(__weak id object, id oldValue, id newValue) {
                                NSLog(@"newValue ==%@",newValue);
                                BOOL isHidden = [(NSNumber *)newValue boolValue];
                                dispatch_async(dispatch_get_main_queue(), ^{
//                                    [self.navigationController setNavigationBarHidden:isHidden animated:YES];
                                    [self.closeControl setHidden:isHidden];
                                });

                            }];
                            break;
                        }
                    }
                }
            }
        }

    } error:nil];
#pragma clang diagnostic pop
    //这里必须监听到准备好开始播放了,才把按钮添加上去(系统控件的懒加载机制,我们才能获取到合适的 view 去添加),不然很突兀!
    [self.playerVC.player HF_addObserverForKeyPath:@"status" block:^(__weak id object, id oldValue, id newValue) {
        AVPlayerStatus status = [newValue integerValue];
        if (status == AVPlayerStatusReadyToPlay) {
            UIView *avTouchIgnoringView = self->_playerVC.view;
            [avTouchIgnoringView addSubview:self.closeControl];
    //这里判断是否刘海屏,不同机型的放置位置不一样!
            BOOL ishairScreen = [self.view isHairScreen];
            CGFloat margin = ishairScreen ?90:69;
            [self.closeControl mas_makeConstraints:^(MASConstraintMaker *make) {
                make.right.mas_equalTo(avTouchIgnoringView).offset(-margin);
                make.top.mas_equalTo(avTouchIgnoringView).offset(ishairScreen ?27:6);
                make.width.mas_equalTo(60);
                make.height.mas_equalTo(47);
            }];
            [avTouchIgnoringView setNeedsLayout];
        }
    }];

    if (self.playerVC.readyForDisplay) {
        [self.playerVC.player play];
    }

}

//别忘了释放资源
- (void)dealloc
{
    self.playerVC = nil;
}


来来来,上图:



close按钮和原生工具栏同步显示和隐藏


至此,大功告成了,不过同步显示和隐藏过程需要大家自己去摸索合适的动画了,我总是踏不准点!当然,横竖屏和强制横屏的方案我这里也大概提一下吧,主要思路是监听屏幕的旋转通知:


//获取设备旋转方向的通知,即使关闭了自动旋转,一样可以监测到设备的旋转方向
        [[UIDevice currentDevice] beginGeneratingDeviceOrientationNotifications];
        //旋转屏幕通知
        [[NSNotificationCenter defaultCenter] addObserver:self
                                                 selector:@selector(onDeviceOrientationChange:)
                                                     name:UIDeviceOrientationDidChangeNotification
                                                   object:nil
         ];

/**
 *  旋转屏幕通知
 */

- (void)onDeviceOrientationChange:(NSNotification *)notification{

    UIDeviceOrientation orientation = [UIDevice currentDevice].orientation;
    UIInterfaceOrientation interfaceOrientation = (UIInterfaceOrientation)orientation;
    switch (interfaceOrientation) {
        case UIInterfaceOrientationPortraitUpsideDown:{

        }
            break;
        case UIInterfaceOrientationPortrait:
            [self changeOrientation:UIInterfaceOrientationPortrait];
        }
            break;
        case UIInterfaceOrientationLandscapeLeft:
            [self changeOrientation:UIInterfaceOrientationLandscapeLeft];
        }
            break;
        case UIInterfaceOrientationLandscapeRight:{
            [self changeOrientation:UIInterfaceOrientationLandscapeRight];
        }
            break;
        default:
            break;
    }
}

-(void)changeOrientation:(UIInterfaceOrientation)orientation{
    if (orientation == UIInterfaceOrientationPortrait) {
        [self setNeedsStatusBarAppearanceUpdate];
        [self forceOrientationPortrait];

    }else{
        [self setNeedsStatusBarAppearanceUpdate];
        [self forceOrientationLandscape];
    }

    if (@available(iOS 11.0, *)) {
        [self setNeedsUpdateOfHomeIndicatorAutoHidden];
    }
    //刷新
    [UIViewController attemptRotationToDeviceOrientation];
}

//强制横屏
- (void)forceOrientationLandscape
{
      [[UIApplication sharedApplication].delegate.isForceLandscape = YES;
      [[UIApplication sharedApplication].delegate.isForcePortrait = NO;
      [[UIApplication sharedApplication].delegate  application:[UIApplication sharedApplication] supportedInterfaceOrientationsForWindow:self.view.window];
}

//强制竖屏
- (void)forceOrientationPortrait
{

     [[UIApplication sharedApplication].delegate.isForceLandscape = NO;
     [[UIApplication sharedApplication].delegate.isForcePortrait = YES;
     [[UIApplication sharedApplication].delegate application:[UIApplication sharedApplication] supportedInterfaceOrientationsForWindow:self.view.window];
}


在 AppDelegate.h 里面添加以下属性


#import 

@interface AppDelegate : UIResponder < UIApplicationDelegate>

@property (strongnonatomicUIWindow *window;
//添加旋转需要的属性
@property (nonatomicassignBOOL isForceLandscape;
@property (nonatomicassignBOOL isForcePortrait;
@end


在 AppDelegate.m 里面实现以下方法


-(UIInterfaceOrientationMask)application:(UIApplication *)application supportedInterfaceOrientationsForWindow:(UIWindow *)window{
    if (self.isForceLandscape) {
        return UIInterfaceOrientationMaskLandscape;
    }else if (self.isForcePortrait){
        return UIInterfaceOrientationMaskPortrait;
    }
    return UIInterfaceOrientationMaskPortrait;
}


今天的小菜逼装完了,总感觉自己在这个行业里瑟瑟发抖,找不到上岸的路!


demo地址


https://github.com/THandsonwu/AVPlayerViewControllerDemo


 推荐↓↓↓ 

?16个技术公众号】都在这里!

涵盖:程序员大咖、源码共读、程序员共读、数据结构与算法、黑客技术和网络安全、大数据科技、编程前端、Java、Python、Web编程开发、Android、iOS开发、Linux、数据库研发、幽默程序员等。

万水千山总是情,点个 “好看” 行不行

关注公众号:拾黑(shiheibook)了解更多

[广告]赞助链接:

四季很好,只要有你,文娱排行榜:https://www.yaopaiming.com/
让资讯触达的更精准有趣:https://www.0xu.cn/

公众号 关注网络尖刀微信公众号
随时掌握互联网精彩
赞助链接