iOS系統(tǒng)錄屏-ReplayKit框架

ReplayKit框架說明

  • ReplayKit框架是蘋果提供的錄制視頻的框架.
  • 優(yōu)點(diǎn):錄制流暢不卡頓
  • 缺點(diǎn):
  • 不能定制預(yù)覽頁面
  • 如果再次錄制開始時(shí)間距離上次錄制完成時(shí)間超過8分鐘,還會(huì)彈框提示錄制權(quán)限
  • 默認(rèn)保存到相冊,不能指定保存路徑.
  • ReplayKit只支持ios9+,部分最新函數(shù)只支持10+

開始錄制

  • #import <ReplayKit/ReplayKit.h>
  • 添加代理 <RPScreenRecorderDelegate, RPPreviewViewControllerDelegate>
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSKeyValueChangeKey,id> *)change context:(void *)context
{
    if ([keyPath isEqualToString:@"recording"]) {
        NSLog(@"keyPath === %@",object);
        if ([change valueForKey:@"recording"] == 0) {
            NSLog(@"可以錄制");
        }else
        {
            NSLog(@"++++++++++++不可以");
        }
    }
}

//開始錄屏
- (void)startRecoding
{
    //將開啟錄屏功能的代碼放在主線程執(zhí)行
//    __weak typeof (self)weakSelf = self;
    dispatch_async(dispatch_get_main_queue(), ^{
        if ([[RPScreenRecorder sharedRecorder] isAvailable] && [self isSystemVersionOk]) { //判斷硬件和ios版本是否支持錄屏
            NSLog(@"支持ReplayKit錄制");
            //這是錄屏的類
            RPScreenRecorder* recorder = RPScreenRecorder.sharedRecorder;
            recorder.delegate = self;
            
            //開起錄屏功能
            //9.0+函數(shù)(在10+版本被廢棄,替換為startRecordingWithHandler:)
            [recorder startRecordingWithMicrophoneEnabled:YES handler:^(NSError * _Nullable error) {
                recorder.microphoneEnabled = YES;
                if (error) {
                    IsDecoderScreen = 0;
                    NSLog(@"========%@",error.description);
                    [self showAlert:@"錄制失敗" andMessage:@"啟動(dòng)錄制失敗請重試!"];
                    startRecordScreenBtn.backgroundColor = [UIColor greenColor];
                    [startRecordScreenBtn setTitle:@"錄屏" forState:UIControlStateNormal];
                } else {
                    if (recorder.recording) {
                        startRecordScreenBtn.backgroundColor = [UIColor redColor];
                        [startRecordScreenBtn setTitle:@"結(jié)束錄屏" forState:UIControlStateNormal];
                        //記錄是否開始錄屏 系統(tǒng)也有一個(gè)再帶的檢測是否在錄屏的方法 (@property (nonatomic, readonly, getter=isRecording) BOOL recording;)
                        IsDecoderScreen = 1;
                    }
                }
            }];
            //10.0+函數(shù)
            //在此可以設(shè)置是否允許麥克風(fēng)(傳YES即是使用麥克風(fēng),傳NO則不是用麥克風(fēng))
            //            recorder.microphoneEnabled = YES;
            //            recorder.cameraEnabled = YES;
//            [recorder startRecordingWithHandler:^(NSError * _Nullable error) {
//                
//                //在此可以設(shè)置是否允許麥克風(fēng)(傳YES即是使用麥克風(fēng),傳NO則不是用麥克風(fēng))(ios 后被廢棄了 下面的這個(gè)開始錄屏)
//                //            [recorder startRecordingWithMicrophoneEnabled:YES handler:^(NSError * _Nullable error) {
//                recorder.microphoneEnabled = YES;
//                if (error) {
//                    IsDecoderScreen = 0;
//                    NSLog(@"========%@",error.description);
//                    [self showAlert:@"錄制失敗" andMessage:@"啟動(dòng)錄制失敗請重試!"];
//                    startRecordScreenBtn.backgroundColor = [UIColor greenColor];
//                    [startRecordScreenBtn setTitle:@"錄屏" forState:UIControlStateNormal];
//                } else {
//                    if (recorder.recording) {
//                        startRecordScreenBtn.backgroundColor = [UIColor redColor];
//                        [startRecordScreenBtn setTitle:@"結(jié)束錄屏" forState:UIControlStateNormal];
//                        //記錄是否開始錄屏 系統(tǒng)也有一個(gè)再帶的檢測是否在錄屏的方法 (@property (nonatomic, readonly, getter=isRecording) BOOL recording;)
//                        IsDecoderScreen = 1;
//                    }
//                }
//            }];
        } else {
            [self showAlert:@"設(shè)備不支持錄制" andMessage:@"升級(jí)ios系統(tǒng)"];
            return;
        }
    });
    
}

結(jié)束錄制

//結(jié)束錄屏
- (void)stopRecording
{
    __weak typeof (self)weakSelf = self;
    [[RPScreenRecorder sharedRecorder] stopRecordingWithHandler:^(RPPreviewViewController *previewViewController, NSError *  error){
        _RPPreview = previewViewController;
        if (error) {
            NSLog(@"這里關(guān)閉有誤%@",error.description);
            [self showAlert:@"結(jié)束錄制失敗" andMessage:@"本次保存失敗!請重新錄制"];
            startRecordScreenBtn.backgroundColor = [UIColor greenColor];
            [startRecordScreenBtn setTitle:@"錄屏" forState:UIControlStateNormal];
        } else {
            [_RPPreview setPreviewControllerDelegate:self];
            startRecordScreenBtn.backgroundColor = [UIColor greenColor];
            [startRecordScreenBtn setTitle:@"錄屏" forState:UIControlStateNormal];
            IsDecoderScreen = 0;
            //在結(jié)束錄屏?xí)r顯示預(yù)覽畫面
            [weakSelf showVideoPreviewController:_RPPreview withAnimation:YES];
        }
    }];
}

預(yù)覽保存/取消

//顯示視頻預(yù)覽頁面,animation=是否要?jiǎng)赢嬶@示
- (void)showVideoPreviewController:(RPPreviewViewController *)previewController withAnimation:(BOOL)animation {
    if (previewController==nil) {
        return;
    }
    __weak typeof (self) weakSelf = self;
    //UI需要放到主線程
    dispatch_async(dispatch_get_main_queue(), ^{
        CGRect rect = previewController.view.frame;
        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;
            } completion:^(BOOL finished){
            }];
        } else {
            previewController.view.frame = rect;
        }
        
        [weakSelf.view addSubview:previewController.view];
        [weakSelf addChildViewController:previewController];
    });
}

//關(guān)閉視頻預(yù)覽頁面,animation=是否要?jiǎng)赢嬶@示
- (void)hideVideoPreviewController:(RPPreviewViewController *)previewController withAnimation:(BOOL)animation {
    //UI需要放到主線程
    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];
        }
    });
}

ReplayKit代理實(shí)現(xiàn)

#pragma mark - RPPreviewViewControllerDelegate
//關(guān)閉的回調(diào)
- (void)previewControllerDidFinish:(RPPreviewViewController *)previewController {
    if (isSave == 1) {
        //這個(gè)地方我添加了一個(gè)延時(shí),我發(fā)現(xiàn)這樣保存不到系統(tǒng)相冊的情況好多了
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(4 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [self hideVideoPreviewController:_RPPreview withAnimation:YES];
        });
        
        isSave = 0;
    }else {
        dispatch_async(dispatch_get_main_queue(), ^{
            UIAlertAction *queding = [UIAlertAction actionWithTitle:@"確定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                [self hideVideoPreviewController:_RPPreview withAnimation:YES];
                //                dispatch_async(dispatch_get_main_queue(), ^{
                //                                [weakSelf.RPPreview dismissViewControllerAnimated:YES completion:nil];
                //                            });
                isSave = 0;
            }];
            UIAlertAction *actionCancel = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil];
            UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"提示" message:@"錄制未保存\n確定要取消嗎" preferredStyle:UIAlertControllerStyleAlert];
            
            [alert addAction:actionCancel];
            [alert addAction:queding];
            [self presentViewController:alert animated:NO completion:nil];
        });
    }
}
//選擇了某些功能的回調(diào)(如分享和保存)
- (void)previewController:(RPPreviewViewController *)previewController didFinishWithActivityTypes:(NSSet <NSString *> *)activityTypes {
    __weak typeof (self)weakSelf = self;
    if ([activityTypes containsObject:@"com.apple.UIKit.activity.SaveToCameraRoll"]) {
        isSave = 1;
        NSLog(@"***************************");
        //這個(gè)地方我延時(shí)執(zhí)行,等預(yù)覽畫面移除后再顯示提示框
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(4 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            dispatch_async(dispatch_get_main_queue(), ^{
                [weakSelf showAlert:@"保存成功" andMessage:@"已經(jīng)保存到系統(tǒng)相冊"];
                [self uploadVideoAsyn];//上傳數(shù)據(jù)
            });
        });
    }
    if ([activityTypes containsObject:@"com.apple.UIKit.activity.CopyToPasteboard"]) {
        dispatch_async(dispatch_get_main_queue(), ^{
            [weakSelf showAlert:@"復(fù)制成功" andMessage:@"已經(jīng)復(fù)制到粘貼板"];
        });
    }
}

#pragma mark ====RPScreenDelegate===
- (void)screenRecorderDidChangeAvailability:(RPScreenRecorder *)screenRecorder
{
    //    [screenRecorder addObserver:self forKeyPath:@"recording" options:NSKeyValueObservingOptionNew context:nil];
    //    [screenRecorder setValue:@"1" forKey:@"recording"];
    NSLog(@" delegate ======%@",screenRecorder);
}

- (void)screenRecorder:(RPScreenRecorder *)screenRecorder didStopRecordingWithError:(NSError *)error previewViewController:(nullable RPPreviewViewController *)previewViewController
{
    [_RPPreview setPreviewControllerDelegate:self];
    startRecordScreenBtn.backgroundColor = [UIColor greenColor];
    [startRecordScreenBtn setTitle:@"錄屏" forState:UIControlStateNormal];
    IsDecoderScreen = 0;
    [self showVideoPreviewController:_RPPreview withAnimation:YES];
}

其他補(bǔ)充方法

//顯示彈框提示
- (void)showAlert:(NSString *)title andMessage:(NSString *)message {
    if (!title) {
        title = @"";
    }
    if (!message) {
        message = @"";
    }
    UIAlertAction *actionCancel = [UIAlertAction actionWithTitle:@"好的" style:UIAlertActionStyleCancel handler:nil];
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:title message:message preferredStyle:UIAlertControllerStyleAlert];
    [alert addAction:actionCancel];
    [self presentViewController:alert animated:NO completion:nil];
}

//判斷對應(yīng)系統(tǒng)版本是否支持ReplayKit
- (BOOL)isSystemVersionOk {
    if ([[UIDevice currentDevice].systemVersion floatValue] < 9.0) {
        return NO;
    } else {
        return YES;
    }
}

相冊轉(zhuǎn)移到沙盒并從沙盒上傳到服務(wù)器

  • 保存到相冊后就能把數(shù)據(jù)轉(zhuǎn)到沙盒,從而上傳到服務(wù)器了
  • (void)uploadVideoAsyn{}
  • 實(shí)現(xiàn)思路,參照我的另一篇文章:
    《Photos庫-相冊中視頻轉(zhuǎn)到沙盒》 http://www.itdecent.cn/p/e63ae8d90c3a

githubDemo 地址: https://github.com/KrystalNa/LNRecordingScreen

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • 發(fā)現(xiàn) 關(guān)注 消息 iOS 第三方庫、插件、知名博客總結(jié) 作者大灰狼的小綿羊哥哥關(guān)注 2017.06.26 09:4...
    肇東周閱讀 15,251評(píng)論 4 61
  • Swift版本點(diǎn)擊這里歡迎加入QQ群交流: 594119878最新更新日期:18-09-17 About A cu...
    ylgwhyh閱讀 26,048評(píng)論 7 249
  • WebSocket-Swift Starscream的使用 WebSocket 是 HTML5 一種新的協(xié)議。它實(shí)...
    香橙柚子閱讀 24,743評(píng)論 8 183
  • 點(diǎn)進(jìn)去才發(fā)現(xiàn)也是青青綠蘿裙寫的,依然是喜歡的男主類型,雖然重生,重點(diǎn)還是日常,報(bào)仇基本沒有,就是結(jié)束的有點(diǎn)倉促。女...
    悠然逛南山閱讀 403評(píng)論 0 0
  • 1.English pod2h 2.考研英語1h 3.泛聽felicity20min 今天逛了好長時(shí)間淘寶,注意你...
    cleddie閱讀 172評(píng)論 0 0

友情鏈接更多精彩內(nèi)容