iOS 细节大集合网络iOS

iOS 一行代码实现手机录屏功能

2017-09-14  本文已影响728人  捷风

iOS9以后苹果推出ReplayKit框架,专门用来实现手机录屏功能,所以想要实现录屏功能再也不需要配置第三方了,下面是我实现的效果图,敬请欣赏!👇

录屏.gif

借鉴网上的资料和苹果API文档后,我把这个小功能封装成为一个工具类,需要的时候,只需要在appdelegeta的代理方法中调用一个方法,参数传YES 时 屏幕上面显示按钮,参数为NO时隐藏按钮,接下来看看调用:
AppDelegate.m

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    [[FJReplayKit sharedReplay] catreButton:YES];
}

再来看看工具类FJReplayKit中的代码实现,这里就附上demo了,如果哪位小伙伴需要看看效果,只需要创建一个新工程,然后创建一个工具类,把FJReplayKit.h和FJReplayKit.m中的代码直接复制到项目中,在上面调用的地方加上哪一行代码,然后运行后就可以见证奇迹了,在这里稍微提醒下,测试的时候最好到真机上面运行,因为我之前在模拟器上面运行的时候偶尔会出现结束后不弹出预览页面的情况,具体原因还没找到,如果哪位知道原因,欢迎给我留言,谢谢!
好了废话不多说,下面就来看看实现代码吧!
FJReplayKit.h

#import <Foundation/Foundation.h>
#import <UIKit/UIKit.h>
#import <ReplayKit/ReplayKit.h>

@protocol FJReplayDelegate <NSObject>
@optional
/**
 *  开始录制回调
 */
-(void)replayRecordStart;
/**
 *  录制结束或错误回调
 */
-(void)replayRecordFinishWithVC:(RPPreviewViewController *)previewViewController errorInfo:(NSString *)errorInfo;
/**
 *  保存到系统相册成功回调
 */
-(void)saveSuccess;
@end

//系统版本需要是iOS9.0及以上才支持ReplayKit框架录制
@interface FJReplayKit : NSObject
/**
 *  代理
 */
@property (nonatomic,weak) id <FJReplayDelegate> delegate;
/**
 *  是否正在录制
 */
@property (nonatomic,assign,readonly) BOOL isRecording;
/**
 *  单例对象
 */
+(instancetype)sharedReplay;
/**
 是否显示录制按钮
 */
-(void)catreButton:(BOOL)iscate;
/**
 *  开始录制
 */
-(void)startRecord;
/**
 *  结束录制
 *  isShow是否录制完后自动展示视频预览页
 */
-(void)stopRecordAndShowVideoPreviewController:(BOOL)isShow;
@end

FJReplayKit.m


#import "FJReplayKit.h"

@interface FJReplayKit ()<RPPreviewViewControllerDelegate>
/**开始录制*/
@property (nonatomic,strong)UIButton *startBt;
/**结束录制*/
@property (nonatomic,strong)UIButton *endBt;
@property(strong,nonatomic)UIWindow *window;
@end

@implementation FJReplayKit
#pragma mark ---懒加载
-(UIButton*)startBt{
    if(!_startBt){
        _startBt=[[UIButton alloc] initWithFrame:CGRectMake(0,0,80,50)];
        _startBt.backgroundColor=[UIColor redColor];
        [_startBt setTitle:@"开始录制" forState:UIControlStateNormal];
        _startBt.titleLabel.font=[UIFont systemFontOfSize:14];
        [_startBt addTarget:self action:@selector(startAction) forControlEvents:UIControlEventTouchUpInside];
    }
    return _startBt;
}
-(UIButton*)endBt{
    if(!_endBt){
        _endBt=[[UIButton alloc] initWithFrame:CGRectMake(0,60,80,50)];
        _endBt.backgroundColor=[UIColor redColor];
        [_endBt setTitle:@"结束录制" forState:UIControlStateNormal];
        _endBt.titleLabel.font=[UIFont systemFontOfSize:14];
        [_endBt addTarget:self action:@selector(endAction) forControlEvents:UIControlEventTouchUpInside];
    }
    return _endBt;
}
/**
 是否显示录制按钮
 */
-(void)catreButton:(BOOL)iscate{
    if (!iscate) return;
    [self performSelector:@selector(createWidow) withObject:nil afterDelay:1];
}
-(void)createWidow{
    self.window =[[UIWindow alloc]initWithFrame:CGRectMake(0, 100, 80, 120)];
    self.window.backgroundColor=[UIColor clearColor];
    self.window.windowLevel = UIWindowLevelAlert+1;
    [self.window makeKeyAndVisible];
    [self.window addSubview:self.startBt];
    [self.window addSubview:self.endBt];
}
//单例化对象
+(instancetype)sharedReplay{
    static FJReplayKit *replay=nil;
    static dispatch_once_t token;
    dispatch_once(&token, ^{
        replay=[[FJReplayKit alloc] init];
    });
    return replay;
}
-(void)startAction{
    [_startBt setTitle:@"初始化中" forState:UIControlStateNormal];
    [[FJReplayKit sharedReplay] startRecord];
}
-(void)endAction{
    [_startBt setTitle:@"开始录制" forState:UIControlStateNormal];
    [[FJReplayKit sharedReplay] stopRecordAndShowVideoPreviewController:YES];
}
//是否正在录制
-(BOOL)isRecording{
    return [RPScreenRecorder sharedRecorder].recording;
}
#pragma mark - 开始/结束录制
//开始录制
-(void)startRecord{
    if ([RPScreenRecorder sharedRecorder].recording==YES) {
        DLog(@"FJReplayKit:已经开始录制");
        return;
    }
    if ([self systemVersionOK]) {
        if ([[RPScreenRecorder sharedRecorder] isAvailable]) {
            DLog(@"FJReplayKit:录制开始初始化");
            [[RPScreenRecorder sharedRecorder] startRecordingWithMicrophoneEnabled:YES handler:^(NSError *error){
                if (error) {
                    DLog(@"FJReplayKit:开始录制error %@",error);
                    if ([_delegate respondsToSelector:@selector(replayRecordFinishWithVC:errorInfo:)]) {
                        [_delegate replayRecordFinishWithVC:nil errorInfo:[NSString stringWithFormat:@"FJReplayKit:开始录制error %@",error]];
                    }
                }else{
                    DLog(@"FJReplayKit:开始录制");
                    [self.startBt setTitle:@"正在录制" forState:UIControlStateNormal];
                    if ([_delegate respondsToSelector:@selector(replayRecordStart)]) {
                        [_delegate replayRecordStart];
                    }
                }
            }];
        }
        else {
            DLog(@"FJReplayKit:环境不支持ReplayKit录制");
            if ([_delegate respondsToSelector:@selector(replayRecordFinishWithVC:errorInfo:)]) {
                [_delegate replayRecordFinishWithVC:nil errorInfo:@"FJReplayKit:环境不支持ReplayKit录制"];
            }
        }
    }
    else{
        DLog(@"FJReplayKit:系统版本需要是iOS9.0及以上才支持ReplayKit录制");
        if ([_delegate respondsToSelector:@selector(replayRecordFinishWithVC:errorInfo:)]) {
            [_delegate replayRecordFinishWithVC:nil errorInfo:@"FJReplayKit:系统版本需要是iOS9.0及以上才支持ReplayKit录制"];
        }
    }
}
//结束录制
-(void)stopRecordAndShowVideoPreviewController:(BOOL)isShow{
    DLog(@"FJReplayKit:正在结束录制");
    [[RPScreenRecorder sharedRecorder] stopRecordingWithHandler:^(RPPreviewViewController *previewViewController, NSError *  error){
        [self.startBt setTitle:@"开始录制" forState:UIControlStateNormal];
        if (error) {
            DLog(@"FJReplayKit:结束录制error %@", error);
            if ([_delegate respondsToSelector:@selector(replayRecordFinishWithVC:errorInfo:)]) {
                [_delegate replayRecordFinishWithVC:nil errorInfo:[NSString stringWithFormat:@"FJReplayKit:结束录制error %@",error]];
            }
        }
        else {
            DLog(@"FJReplayKit:录制完成");
            if ([_delegate respondsToSelector:@selector(replayRecordFinishWithVC:errorInfo:)]) {
                [_delegate replayRecordFinishWithVC:previewViewController errorInfo:@""];
            }
            if (isShow) {
                [self showVideoPreviewController:previewViewController animation:YES];
            }
        }
    }];
}
#pragma mark - 显示/关闭视频预览页
//显示视频预览页面
-(void)showVideoPreviewController:(RPPreviewViewController *)previewController animation:(BOOL)animation {
    previewController.previewControllerDelegate=self;
    __weak UIViewController *rootVC=[self getRootVC];
    dispatch_async(dispatch_get_main_queue(), ^{
        CGRect rect = [UIScreen mainScreen].bounds;
        if (animation) {
            rect.origin.x+=rect.size.width;
            previewController.view.frame=rect;
            rect.origin.x-=rect.size.width;
            [UIView animateWithDuration:0.3 animations:^(){
                previewController.view.frame=rect;
            }];
        }
        else{
            previewController.view.frame=rect;
        }
        
        [rootVC.view addSubview:previewController.view];
        [rootVC addChildViewController:previewController];
    });
}
//关闭视频预览页面
-(void)hideVideoPreviewController:(RPPreviewViewController *)previewController animation:(BOOL)animation {
    previewController.previewControllerDelegate=nil;
    dispatch_async(dispatch_get_main_queue(), ^{
        CGRect rect = previewController.view.frame;
        if (animation) {
            rect.origin.x+=rect.size.width;
            [UIView animateWithDuration:0.3 animations:^(){
                previewController.view.frame=rect;
            }completion:^(BOOL finished){
                [previewController.view removeFromSuperview];
                [previewController removeFromParentViewController];
            }];
        }
        else{
            [previewController.view removeFromSuperview];
            [previewController removeFromParentViewController];
        }
    });
}
#pragma mark - 视频预览页回调
//关闭的回调
- (void)previewControllerDidFinish:(RPPreviewViewController *)previewController {
    [self hideVideoPreviewController:previewController animation:YES];
}
//选择了某些功能的回调(如分享和保存)
- (void)previewController:(RPPreviewViewController *)previewController didFinishWithActivityTypes:(NSSet <NSString *> *)activityTypes {
    if ([activityTypes containsObject:@"com.apple.UIKit.activity.SaveToCameraRoll"]) {
        DLog(@"FJReplayKit:保存到相册成功");
        if ([_delegate respondsToSelector:@selector(saveSuccess)]) {
            [_delegate saveSuccess];
        }
    }
    if ([activityTypes containsObject:@"com.apple.UIKit.activity.CopyToPasteboard"]) {
        DLog(@"FJReplayKit:复制成功");
    }
}
#pragma mark - 其他方法
//判断对应系统版本是否支持ReplayKit
-(BOOL)systemVersionOK{
    if ([[UIDevice currentDevice].systemVersion floatValue]<9.0) {
        return NO;
    } else {
        return YES;
    }
}
//获取rootVC
-(UIViewController *)getRootVC{
    return [UIApplication sharedApplication].delegate.window.rootViewController;
}
@end

总结:好了,上面就是实现代码了,赶快去写个demo体验一下吧,在写这个文章的时候我一直在思考一个问题,就是目前我这个只能实现在自己APP内实现录屏,不知有没有办法实现自己写的APP退出后台还能对手机桌面和其他APP内部进行录制,如果哪位有好的思路和想法,请给我留言或者私信,万分感谢!🙏🙏🙏

上一篇 下一篇

猜你喜欢

热点阅读