iOS 使用AFN上传视频到服务器示例代码
这里介绍用AFN上传本地拍摄的视频到服务端。
整体思路:拿到视频资源,先转为mp4,写进沙盒,然后上传,上传成功后要记得删除沙盒中的文件。
压缩导出视频
//视频转换为MP4 //转码操作... _hud.mode=MBProgressHUDModeIndeterminate; _hud.labelText=@"转码中..."; AVURLAsset*avAsset=[AVURLAssetURLAssetWithURL:_filePathURLoptions:nil]; NSDateFormatter*formater=[[NSDateFormatteralloc]init]; [formatersetDateFormat:@"yyyyMMddHHmmss"]; _fileName=[NSStringstringWithFormat:@"output-%@.mp4",[formaterstringFromDate:[NSDatedate]]]; _outfilePath=[NSHomeDirectory()stringByAppendingFormat:@"/Documents/%@",_fileName]; NSArray*compatiblePresets=[AVAssetExportSessionexportPresetsCompatibleWithAsset:avAsset]; if([compatiblePresetscontainsObject:AVAssetExportPresetMediumQuality]){ MyLog(@"outPath=%@",_outfilePath); AVAssetExportSession*exportSession=[[AVAssetExportSessionalloc]initWithAsset:avAssetpresetName:AVAssetExportPresetMediumQuality]; exportSession.outputURL=[NSURLfileURLWithPath:_outfilePath]; exportSession.outputFileType=AVFileTypeMPEG4; [exportSessionexportAsynchronouslyWithCompletionHandler:^{ if([exportSessionstatus]==AVAssetExportSessionStatusCompleted){ MyLog(@"AVAssetExportSessionStatusCompleted---转换成功"); _filePath=_outfilePath; _filePathURL=[NSURLURLWithString:[NSStringstringWithFormat:@"file://%@",_outfilePath]]; MyLog(@"转换完成_filePath=%@\\n_filePathURL=%@",_filePath,_filePathURL); //获取大小和长度 [selfSetViewText]; [selfuploadNetWorkWithParam:@{@"contenttype":@"application/octet-stream",@"discription":description}]; }else{ MyLog(@"转换失败,值为:%li,可能的原因:%@",(long)[exportSessionstatus],[[exportSessionerror]localizedDescription]); [_hudhide:YES]; [MyHelpershowAlertWith:niltxt:@"转换失败,请重试"]; } }]; }
开始上传
-(void)uploadNetWorkWithParam:(NSDictionary*)dict{ MyLog(@"开始上传_filePath=%@\\n_filePathURL=%@",_filePath,_filePathURL); AFHTTPRequestSerializer*ser=[[AFHTTPRequestSerializeralloc]init]; NSMutableURLRequest*request= [sermultipartFormRequestWithMethod:@"POST" URLString:[NSStringstringWithFormat:@"%@%@",kBaseUrl,kVideoUploadUrl] parameters:@{@"path":@"show",@"key":_key,@"discription":dict[@"discription"],@"isimage":@(_isImage)} constructingBodyWithBlock:^(idformData){ [formDataappendPartWithFileURL:_filePathURLname:@"file"fileName:_fileNamemimeType:dict[@"contenttype"]error:nil]; if(!_isImage){ [formDataappendPartWithFileURL:_path2Urlname:@"tmp"fileName:@"tmp.PNG"mimeType:@"image/png"error:nil]; } }error:nil]; //@"image/png"@"application/octet-stream"mimeType AFURLSessionManager*manager=[[AFURLSessionManageralloc]initWithSessionConfiguration:[NSURLSessionConfigurationdefaultSessionConfiguration]]; NSProgress*progress=nil; NSURLSessionUploadTask*uploadTask=[manageruploadTaskWithStreamedRequest:requestprogress:&progresscompletionHandler:^(NSURLResponse*response,idresponseObject,NSError*error){ if(error){ MyLog(@"request=%@",request); MyLog(@"response=%@",response); MyLog(@"Error:%@",error); [_hudhide:YES]; CXAlertView*alert=[[CXAlertViewalloc]initWithTitle:NSLocalizedString(@"Warning",nil) message:NSLocalizedString(@"UploadFailed",nil) cancelButtonTitle:NSLocalizedString(@"Iknow",nil)]; alert.showBlurBackground=NO; [alertshow]; }else{ MyLog(@"%@%@",response,responseObject); NSDictionary*backDict=(NSDictionary*)responseObject; if([backDict[@"success"]boolValue]!=NO){ _hud.labelText=NSLocalizedString(@"Updating",nil); [selfUpdateResxDateWithDict:backDictdiscription:dict[@"discription"]]; [_hudhide:YES]; }else{ [_hudhide:YES]; [MyHelpershowAlertWith:niltxt:backDict[@"msg"]]; } } [progressremoveObserver:self forKeyPath:@"fractionCompleted" context:NULL]; }]; [progressaddObserver:self forKeyPath:@"fractionCompleted" options:NSKeyValueObservingOptionNew context:NULL]; [progresssetUserInfoObject:@"someThing"forKey:@"Y.X."]; [uploadTaskresume]; }
清除documents中视频
-(void)ClearMovieFromDoucments{ NSFileManager*fileManager=[NSFileManagerdefaultManager]; NSArray*paths=NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask,YES); NSString*documentsDirectory=[pathsobjectAtIndex:0]; NSArray*contents=[fileManagercontentsOfDirectoryAtPath:documentsDirectoryerror:NULL]; NSEnumerator*e=[contentsobjectEnumerator]; NSString*filename; while((filename=[enextObject])){ MyLog(@"%@",filename); if([filenameisEqualToString:@"tmp.PNG"]){ MyLog(@"删除%@",filename); [fileManagerremoveItemAtPath:[documentsDirectorystringByAppendingPathComponent:filename]error:NULL]; continue; } if([[[filenamepathExtension]lowercaseString]isEqualToString:@"mp4"]|| [[[filenamepathExtension]lowercaseString]isEqualToString:@"mov"]|| [[[filenamepathExtension]lowercaseString]isEqualToString:@"png"]){ MyLog(@"删除%@",filename); [fileManagerremoveItemAtPath:[documentsDirectorystringByAppendingPathComponent:filename]error:NULL]; } } }
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持毛票票。