// // YOUPAIZYSendVideoByLinkVC.m // VQU // // Created by Elaine on 2020/11/9. // Copyright © 2020 leo. All rights reserved. // #import "YOUPAIZYSendVideoByLinkVC.h" #import "UIViewController+TFPresent.h" #import "LZAlertWindow.h" #import "YOUPAILPChatTipView.h" #import "YOUPAIZYSendVideoByLocalVC.h" #import "YOUPAISHMediaManager.h"//直接裁剪类 @interface YOUPAIZYSendVideoByLinkVC () @property (nonatomic,strong)UITextField* youpaiptextField; @property(nonatomic,strong)UIButton *youpaipsendVideoBtn;//发布视频 @property(nonatomic,strong)NSURLSessionDownloadTask *youpaipdownloadTask; @end @implementation YOUPAIZYSendVideoByLinkVC -(void)viewWillAppear:(BOOL)animated{ [super viewWillAppear:animated]; // [self youpaifaddTip]; } - (void)youpaifaddTip{ NSString *tip = @"请勿涉及色情,广告等违规内容,违者将永久封号"; YOUPAILPChatTipView* chatTip = [[YOUPAILPChatTipView alloc]initWithFrame:CGRectMake(0,NavBarHeight-40, KScreenWidth, 40)]; chatTip.tipLabel.text = tip; [self.view addSubview:chatTip]; [UIView animateWithDuration:1 animations:^{ chatTip.frame = CGRectMake(0,NavBarHeight, KScreenWidth, 40); }completion:^(BOOL finished) { if (finished) { dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{ [UIView animateWithDuration:1 animations:^{ chatTip.frame = CGRectMake(0,NavBarHeight-40, KScreenWidth, 40); }completion:^(BOOL finished) { if (finished) { [chatTip removeFromSuperview]; } }]; }); } }]; } - (void)viewDidLoad { [super viewDidLoad]; self.title = @"链接上传"; UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(youpaifhideTheKeyboard)]; [self.view addGestureRecognizer:tap]; // self.view.backgroundColor = HexColorFromRGB(0xFFFFFF); self.navigationItem.leftBarButtonItem = [UIBarButtonItem itemWithTarget:self action:@selector(youpaifcancelClick) image:[UIImage imageNamed:@"vqu_images_navigation_back_black"]]; UIButton *rightBgV = [UIButton buttonWithType:UIButtonTypeCustom]; [rightBgV addTarget:self action:@selector(youpaifrightClick) forControlEvents:UIControlEventTouchUpInside]; UIImageView *rightImgV = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"vqu_images_D_senddynamic_right"]]; rightImgV.frame = CGRectMake(44.0f - 16.0f, (44.0f - 16.0f) / 2.0f, 16.0f, 16.0f); [rightBgV addSubview:rightImgV]; UIBarButtonItem *rightBarItem = [[UIBarButtonItem alloc] initWithCustomView:rightBgV]; self.navigationItem.rightBarButtonItem = rightBarItem;//[UIBarButtonItem itemWithTarget:self action:@selector(youpaifrightClick) image:[UIImage imageNamed:@"ic_senddynamic_right"]]; // ZCLiveTextView* liveView = [[ZCLiveTextView alloc]initWithFrame:CGRectMake(15, 15+NavBarHeight, KScreenWidth-30, 100) TopMargin:8 LeftMargin:8]; // liveView.textLength= 140; // liveView.backgroundColor = [UIColor whiteColor]; // liveView.placeholder = @"这一刻你想说点什么..."; // liveView.placeholderColor = HexColorFromRGB(0xb5b5b5); // liveView.timeoutAlertColor = LCRedColor; // liveView.layer.cornerRadius = 10.0; // self.liveView = liveView; // [self.view addSubview:liveView]; // UILabel *line = [[UILabel alloc] initWithFrame:CGRectMake(16, CGRectGetMaxY(liveView.frame)+16,KScreenWidth - 32,0.5)]; // line.backgroundColor = HexColorFromRGB(0xEEEEEE); // [self.view addSubview:line]; UITextField* textField = [[UITextField alloc]initWithFrame:CGRectMake(14.0f,NavBarHeight + 24.0f, KScreenWidth-28.0f, 48.0f)]; textField.layer.cornerRadius = 5.0f; textField.layer.masksToBounds = YES; textField.clearButtonMode = UITextFieldViewModeWhileEditing; [[textField valueForKey:@"_clearButton"] setImage:[UIImage imageNamed:@"vqu_images_D_nick_clean"] forState:UIControlStateNormal]; textField.font = LCFont(14); textField.textColor = [UIColor whiteColor]; textField.tintColor = ZYGradientTwoColor; self.youpaiptextField = textField; textField.backgroundColor = HexColorFromRGB(0x2A2935); UIView *leftPwdView = [[UIView alloc]initWithFrame:CGRectMake(0, 0,12.0f, 48)]; textField.leftView = leftPwdView; textField.leftViewMode = UITextFieldViewModeAlways; NSString *holderText = @"粘贴抖音或其他平台分享来的视频链接"; NSMutableAttributedString *placeholder = [[NSMutableAttributedString alloc] initWithString:holderText]; [placeholder addAttribute:NSForegroundColorAttributeName value:HexColorFromRGB(0x6C6B70) range:NSMakeRange(0, holderText.length)]; [placeholder addAttribute:NSFontAttributeName value:LCFont(14) range:NSMakeRange(0, holderText.length)]; textField.attributedPlaceholder = placeholder; [self.view addSubview:textField]; self.youpaipsendVideoBtn = [UIButton buttonWithType:UIButtonTypeCustom]; self.youpaipsendVideoBtn.frame = CGRectMake(40.0f,KScreenHeight-SafeHeight-77.0f,KScreenWidth - 80.0f,48); [self.youpaipsendVideoBtn setTitle:@"下一步" forState:0]; [self.youpaipsendVideoBtn setTitleColor:[UIColor whiteColor] forState:0]; self.youpaipsendVideoBtn.titleLabel.font = LCFont(16); self.youpaipsendVideoBtn.layer.cornerRadius = 24; self.youpaipsendVideoBtn.layer.masksToBounds = YES; [self.youpaipsendVideoBtn addTarget:self action:@selector(youpaifsendClick) forControlEvents:UIControlEventTouchUpInside]; self.youpaipsendVideoBtn.backgroundColor = HexColorFromRGB(0x4F4B5B); self.youpaipsendVideoBtn.userInteractionEnabled = NO; [self.view addSubview:self.youpaipsendVideoBtn]; } - (void)youpaifcancelClick{ [self popEffectDismiss]; // // self.sendModel.tit = self.liveView.textView.text; // UIAlertController *alertController = [UIAlertController alertControllerWithTitle:nil message:@"要保存草稿吗?" preferredStyle:UIAlertControllerStyleAlert]; // UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"放弃" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action){ // // [LCSaveModel saveSendDynamicModel:nil]; // [self popEffectDismiss]; // }]; // UIAlertAction *okAction = [UIAlertAction actionWithTitle:@"保存" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action){ // // [LCSaveModel saveSendDynamicModel:self.sendModel]; // [self popEffectDismiss]; // }]; // [alertController addAction:cancelAction]; // [alertController addAction:okAction]; // [self presentViewController:alertController animated:YES completion:nil]; } //提示 -(void)youpaifrightClick{ LZAlertAction *action = [LZAlertAction actionWithTitle:@"我知道了" handler:^(LZAlertAction *action) { }]; action.bgColor = [UIColor colorWithPatternImage:[LCTools ColorImage:CGSizeMake(KScreenWidth - 128.0f, 48.0f) FromColors:@[LZBFB6FFColor,LZ7C69FEColor] ByGradientType:GradientLeftToRight]]; LZAlertWindow *alert = [LZAlertWindow alertWithTitle:@"发布须知" content:@"1、禁止发布色情,性暗示等低俗内容;\n\n2、禁止发布国家政治,暴恐暴乱等内容;\n\n3、不可涉及第三方平台信息;\n\n4、不可使用他人的图片或视频发布。" action:@[action]]; alert.contentFont = LCFont16; alert.contentHorizontalSpace = 32.0f; [self TFPresentVC:alert completion:^{}]; } //发布视频----下载视频到本地 -(void)youpaifsendClick { if (self.youpaiptextField.text.length == 0) { [ZCHUDHelper showTitle:@"链接不能为空"]; return; } NSLog(@"%@",self.youpaiptextField.text); [LCHttpHelper requestWithURLString:Watermark parameters:@{@"shear_plate":self.youpaiptextField.text} needToken:YES type:(HttpRequestTypePost) success:^(id responseObject) { NSDictionary* dict = (NSDictionary*)responseObject; NSInteger code = [[dict objectForKey:@"code"] integerValue]; if (code==0) {//成功 NSString* video_url = [[dict objectForKey:@"data"] objectForKey:@"video_url"]; // NSString* imageUrl = [[dict objectForKey:@"data"] objectForKey:@"image_server"]; NSLog(@"video_url = %@",video_url); [self youpaifstartDownLoadVedioWithUrl:video_url]; } } failure:^(NSError *error) { }]; } /** 下载视频 */ - (void)youpaifstartDownLoadVedioWithUrl:(NSString *)url { NSURLSessionConfiguration *config = [NSURLSessionConfiguration defaultSessionConfiguration]; NSURLSession *session = [NSURLSession sessionWithConfiguration:config delegate:self delegateQueue:[NSOperationQueue mainQueue]]; self.youpaipdownloadTask = [session downloadTaskWithURL:[NSURL URLWithString:url]]; [self.youpaipdownloadTask resume]; [ZCHUDHelper showWithStatus:@"视频下载中..."]; } #pragma mark NSSessionUrlDelegate - (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didWriteData:(int64_t)bytesWritten totalBytesWritten:(int64_t)totalBytesWritten totalBytesExpectedToWrite:(int64_t)totalBytesExpectedToWrite { //下载进度 CGFloat progress = totalBytesWritten / (double)totalBytesExpectedToWrite; dispatch_async(dispatch_get_main_queue(), ^{ //进行UI操作 设置进度条 // self.progressView.progressValue = progress; // self.progressView.contentLabel.text = [NSString stringWithFormat:@"%.2f%%",progress*100]; }); } //下载完成 保存到本地相册 - (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didFinishDownloadingToURL:(NSURL *)location { [ZCHUDHelper showTitle:@"下载完成"]; //1.拿到cache文件夹的路径 NSString *cache=[NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES)lastObject]; //2,拿到cache文件夹和文件名 NSString *file=[cache stringByAppendingPathComponent:downloadTask.response.suggestedFilename]; [[NSFileManager defaultManager] moveItemAtURL:location toURL:[NSURL fileURLWithPath:file] error:nil]; NSLog(@"file = %@",file); //3,保存视频到相册 if (UIVideoAtPathIsCompatibleWithSavedPhotosAlbum(file)) { //保存相册核心代码 UISaveVideoAtPathToSavedPhotosAlbum(file,self,@selector(youpaifsavedVideoPhotoImage:didFinishSavingWithError:contextInfo:),nil); } AVAsset *asset = [AVAsset assetWithURL:[NSURL fileURLWithPath:file]]; CMTime time = [asset duration]; int seconds = ceil(time.value/time.timescale); NSLog(@"视频时长seconds = %d",seconds); UIImage *coverImg = [self youpaifgetLocationVideoPreViewImage:[NSURL fileURLWithPath:file]]; if (seconds > 60) { //视频时长大于60s将自动裁剪前60秒进行上传 [self youpaifisCutVideo:file andImage:coverImg];//是否裁剪视频进行上传 }else{ //裁剪 // YOUPAIVideoEditVC *videoEditVC = [[YOUPAIVideoEditVC alloc] init]; // videoEditVC.videoUrl = [NSURL URLWithString:videoPath]; // [self.navigationController pushViewController:videoEditVC animated:YES]; YOUPAIZYSendVideoByLocalVC *vc = [[YOUPAIZYSendVideoByLocalVC alloc] init]; vc.youpaipcoverImage = coverImg; vc.youpaipvideoFileName = file; [self pushEffectPresentToVC:vc]; } } //自动裁剪视频 -(void)youpaifisCutVideo:(NSString *)videoPath andImage:(UIImage *)coverImage { NSLog(@"videoPath = %@",videoPath); if(!([videoPath rangeOfString:@"://"].location != NSNotFound)) { videoPath = [NSString stringWithFormat:@"file://%@",videoPath]; } NSLog(@"videoPath = %@",videoPath); UIAlertController *alertController = [UIAlertController alertControllerWithTitle:nil message:@"视频时长大于60秒将自动裁剪前60秒进行上传" preferredStyle:UIAlertControllerStyleAlert]; UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消上传" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action){ }]; UIAlertAction *okAction = [UIAlertAction actionWithTitle:@"确定上传" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action){ [ZCHUDHelper showWithStatus:@"正在裁剪..."]; NSURL *url = [NSURL URLWithString:videoPath]; NSLog(@"url == %@",url); [YOUPAISHMediaManager youpaifcropWithVideoUrlStr:url start:1.0 end:60.0 completion:^(NSURL *outputURL, Float64 videoDuration, BOOL isSuccess) { if (isSuccess) { NSLog(@"-转码完成------\n路径:%@",outputURL); dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{ dispatch_async(dispatch_get_main_queue(), ^{ [ZCHUDHelper showTitle:@"裁剪完成" ]; YOUPAIZYSendVideoByLocalVC *vc = [[YOUPAIZYSendVideoByLocalVC alloc] init]; vc.youpaipcoverImage = coverImage; vc.youpaipvideoFileName = [outputURL absoluteString]; [self pushEffectPresentToVC:vc]; }); }); }else{ [ZCHUDHelper showTitle:@"裁剪失败"]; } }]; }]; [alertController addAction:cancelAction]; [alertController addAction:okAction]; [self presentViewController:alertController animated:YES completion:nil]; } //保存视频完成之后的回调 - (void)youpaifsavedVideoPhotoImage:(UIImage*)image didFinishSavingWithError: (NSError*)error contextInfo: (void*)contextInfo { if(error) { NSLog(@"保存视频失败%@", error.localizedDescription);     }else{  NSLog(@"保存视频成功"); // [self youpaifopenAlbum]; } } - (void)youpaifopenAlbum{ TZImagePickerController *imagePickerVc = [[TZImagePickerController alloc] initWithMaxImagesCount:9 columnNumber:4 delegate:nil]; [LCTZImageConfigHelper setDefaultTZImageConfig:imagePickerVc]; imagePickerVc.allowTakePicture = YES; // 在内部显示拍照按钮 imagePickerVc.allowPickingVideo = YES;//是否允许选择视频 imagePickerVc.allowPickingImage = NO;//是否允许选择照片 imagePickerVc.allowPickingOriginalPhoto = NO;//是否选择原图 imagePickerVc.showSelectedIndex = YES; //显示图片序号 // 4. 照片排列按修改时间升序 imagePickerVc.sortAscendingByModificationDate = YES;//按时间倒序排列图片 // 你可以通过block或者代理,来得到用户选择的照片. // [imagePickerVc setDidFinishPickingPhotosHandle:^(NSArray *photos, NSArray *assets, BOOL isSelectOriginalPhoto) { // YOUPAILCSendImageDynamicVC* sendDynamic = [[YOUPAILCSendImageDynamicVC alloc]init]; // YOUPAILCSendDynamicModel* sendModel = [[YOUPAILCSendDynamicModel alloc]init]; // sendModel.images = (NSMutableArray*)photos; // sendDynamic.sendModel = sendModel; // [self pushEffectPresentToVC:sendDynamic]; // }]; // [imagePickerVc setDidFinishPickingGifImageHandle:^(UIImage *animatedImage, id sourceAssets) { // YOUPAILCSendImageDynamicVC* sendDynamic = [[YOUPAILCSendImageDynamicVC alloc]init]; // YOUPAILCSendDynamicModel* sendModel = [[YOUPAILCSendDynamicModel alloc]init]; // sendModel.images = [NSMutableArray arrayWithObject:animatedImage]; // sendDynamic.sendModel = sendModel; // [self pushEffectPresentToVC:sendDynamic]; // }]; [imagePickerVc setDidFinishPickingVideoHandle:^(UIImage *coverImage, PHAsset *asset) { PHVideoRequestOptions *options = [[PHVideoRequestOptions alloc] init]; options.version = PHVideoRequestOptionsVersionOriginal; options.deliveryMode = PHImageRequestOptionsDeliveryModeOpportunistic; options.networkAccessAllowed = YES; [[PHImageManager defaultManager] requestAVAssetForVideo:asset options:nil resultHandler:^(AVAsset * _Nullable asset, AVAudioMix * _Nullable audioMix, NSDictionary * _Nullable info) { AVURLAsset *urlAsser = ( AVURLAsset *)asset; NSString *videoPath =[urlAsser.URL absoluteString]; NSLog(@"%@",videoPath); NSLog(@"%@",info); // [LCHttpHelper requestWithURLString:TrendsSave parameters:@{@"videoFileName":videoPath,@"content":self.liveView.textView.text} needToken:YES type:(HttpRequestTypePost) success:^(id responseObject) { // NSDictionary* dict = (NSDictionary*)responseObject; // NSInteger code = [[dict objectForKey:@"code"] integerValue]; // if (code==0) {//成功 // // } // } failure:^(NSError *error) { // // }]; ///Users/elaine/Library/Developer/CoreSimulator/Devices/BEF0EFD4-9111-484B-861C-ACAF6CDB3E3E/data/Containers/Data/Application/FD1239FA-D00D-4A57-B870-5B00D9FC3C29/Library/Caches/e011cd379dde4be396222e95988f23fd.mp4 //file:///Users/elaine/Library/Developer/CoreSimulator/Devices/BEF0EFD4-9111-484B-861C-ACAF6CDB3E3E/data/Media/DCIM/100APPLE/IMG_0024.mp4 }]; }]; [self presentViewController:imagePickerVc animated:YES completion:nil]; } // 获取本地视频第一帧 - (UIImage*) youpaifgetLocationVideoPreViewImage:(NSURL *)path { AVURLAsset *asset = [[AVURLAsset alloc] initWithURL:path options:nil]; AVAssetImageGenerator *assetGen = [[AVAssetImageGenerator alloc] initWithAsset:asset]; assetGen.appliesPreferredTrackTransform = YES; CMTime time = CMTimeMakeWithSeconds(0.0, 600); NSError *error = nil; CMTime actualTime; CGImageRef image = [assetGen copyCGImageAtTime:time actualTime:&actualTime error:&error]; UIImage *videoImage = [[UIImage alloc] initWithCGImage:image]; CGImageRelease(image); return videoImage; } //隐藏键盘 -(void)youpaifhideTheKeyboard{ dispatch_async(dispatch_get_main_queue(), ^{ [self.youpaiptextField endEditing:YES]; }); if (self.youpaiptextField.text.length != 0) { self.youpaipsendVideoBtn.userInteractionEnabled = YES; [self.youpaipsendVideoBtn setBackgroundImage:[LCTools ColorImage:self.youpaipsendVideoBtn.frame.size FromColors:@[ZYGradientOneColor,ZYGradientTwoColor] ByGradientType:(GradientLeftToRight)] forState:(UIControlStateNormal)]; }else{ self.youpaipsendVideoBtn.userInteractionEnabled = NO; [self.youpaipsendVideoBtn setBackgroundImage:nil forState:(UIControlStateNormal)]; } } @end