ios 开发 添加启动视频

2020-03-27  本文已影响0人  本客

先说一下整体的逻辑,以便更容易理解,首先在Appdelegate中初始化跟视图为视频播放的视图,然后再视频播放完成后或者点击跳过按钮后,再切换跟视图为主页的跟视图,废话不多说,上代码

- (BOOL)application:(UIApplication*)application didFinishLaunchingWithOptions:(NSDictionary*)launchOptions {

    //root视频播放viewController为跟视图

    APPStartViewController * vc =[[APPStartViewController alloc]init];

    self.window.rootViewController=vc;

    [self.window makeKeyAndVisible];

    return YES;

}

#import

#import "APPStartViewController.h"

#import "ViewController.h"

@interface APPStartViewController ()

//关闭视频按钮

@property(nonatomic,strong)UIButton * closeButton;

//播放视频VC

@property(nonatomic,strong)AVPlayerViewController * playLayerVC;

@end

@implementationAPPStartViewController

- (void)viewDidLoad {

    [super viewDidLoad];

    self.view.backgroundColor=[UIColor whiteColor];

    CGSize size = self.view.bounds.size;

    //设置视频的资源URL,我这里用的是本地视频,如果有需要也可以用网上视频,直接拼接网址URL就行

    NSString * urlStr = [[NSBundle mainBundle]pathForResource:@"1585296170657925.mp4" ofType:nil];

    NSURL* url =[NSURL fileURLWithPath:urlStr];

    AVPlayer* player = [[AVPlayer alloc]initWithURL:url];

    //静音模式。默认为NO(非静音)

    player.muted=YES;

    //音量的调节

    player.volume=0;

    AVPlayerViewController * playerVC =[[AVPlayerViewController alloc]init];

   //设置AVPlayerViewController的view视图层为白色,这样就没有屏幕闪烁的毛病了

    playerVC.view.backgroundColor=[UIColor whiteColor];

    playerVC.showsPlaybackControls=NO;

    playerVC.videoGravity=AVLayerVideoGravityResizeAspectFill;

    playerVC.player=player;

    playerVC.view.frame=self.view.bounds;

    [self addChildViewController:playerVC];

    [self.view addSubview:playerVC.view];

    self.playLayerVC= playerVC;

    [playerVC.player play];

    //设置关闭视频按钮

    UIButton * button =[UIButton buttonWithType:UIButtonTypeCustom];

    button.frame=CGRectMake(size.width-80,40,50,50);

    //设置按钮图标

    [button setImage:[UIImage imageNamed:@"皮球.png"] forState:UIControlStateNormal];

    [button addTarget:self action:@selector(videoPlayEnd) forControlEvents:UIControlEventTouchUpInside];

    //关闭按钮添加到最上层的窗口window上

//    [[UIApplication sharedApplication].delegate.window addSubview:button];

    [self.view addSubview:button];

    self.closeButton=button;

    //注册播放结束的监听

    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(videoPlayEnd) name:AVPlayerItemDidPlayToEndTimeNotification object:nil];

}

//实现播放视频结束的方法

-(void)videoPlayEnd{

    //移除通知监听

    [[NSNotificationCenter defaultCenter]removeObserver:self];

    //移除视频

    [self.playLayerVC.view removeFromSuperview];

    //移除Button

    [self.closeButton removeFromSuperview];

    [UIApplication sharedApplication].keyWindow.rootViewController=[ViewController new];

}

上一篇下一篇

猜你喜欢

热点阅读