53rd, OC use AFN upload video to the server

Source: Internet
Author: User

The whole idea has been clear, get the video resources, first to MP4, write into the sandbox, and then upload, upload successfully deleted files in the sandbox.

Locally captured video uploaded to the server:

//convert video to MP4//transcoding Operation ..._hud.mode =mbprogresshudmodeindeterminate; _hud.labeltext=@"transcoding ..."; Avurlasset*avasset =[Avurlasset Urlassetwithurl:_filepathurl Options:nil]; NSDateFormatter* Formater =[[NSDateFormatter alloc] init]; [Formater Setdateformat:@"YYYYMMDDHHMMSS"]; _filename= [NSString stringWithFormat:@"Output-%@.mp4", [formater stringfromdate:[nsdate Date]]; _outfilepath= [Nshomedirectory () Stringbyappendingformat:@"/documents/%@", _filename]; Nsarray*compatiblepresets =[Avassetexportsession Exportpresetscompatiblewithasset:avasset]; if([compatiblepresets containsobject:avassetexportpresetmediumquality]) {MyLog (@"Outpath =%@", _outfilepath); Avassetexportsession*exportsession =[[Avassetexportsession alloc]initwithasset:avasset presetname:avassetexportpresetmediumquality]; Exportsession.outputurl=[Nsurl Fileurlwithpath:_outfilepath]; Exportsession.outputfiletype=AVFileTypeMPEG4; [Exportsession Exportasynchronouslywithcompletionhandler:^{            if([exportsession status] = =avassetexportsessionstatuscompleted) {MyLog (@"avassetexportsessionstatuscompleted---conversion success"); _filepath=_outfilepath; _filepathurl= [Nsurl urlwithstring:[nsstring stringWithFormat:@"file://%@", _outfilepath]]; MyLog (@"conversion Complete _filepath =%@\n_filepathurl =%@", _filepath,_filepathurl); //get size and length[self setviewtext]; [Self uploadnetworkwithparam:@{@"ContentType":@"Application/octet-stream",@"discription":d escription}]; }Else{MyLog (@"conversion failed with a value of:%li, possible cause:%@",(Long) [exportsession status],[[exportsession Error] localizeddescription]);                [_hud Hide:yes]; [Myhelper showalertwith:nil txt:@"conversion failed, please try again"];    }        }]; }#pragmaMark-Start uploading-(void) Uploadnetworkwithparam: (nsdictionary*) dict{MyLog (@"start uploading _filepath =%@\n_filepathurl =%@", _filepath,_filepathurl); Afhttprequestserializer*ser=[[Afhttprequestserializer alloc]init]; Nsmutableurlrequest*request =[ser multipartformrequestwithmethod:@"POST"urlstring:[nsstring stringWithFormat:@"%@%@", Kbaseurl,kvideouploadurl] parameters:@{@"Path":@"Show",@"Key": _key,@"discription":d ict[@"discription"],@"Isimage": @ (_isimage)} Constructingbodywithblock:^(ID<AFMultipartFormData>formData) {[FormData appendpartwithfileurl:_filepathurl name:@"file"Filename:_filename mimetype:dict[@"ContentType"] Error:nil]; if(!_isimage) {[FormData appendpartwithfileurl:_path2url name:@"tmp"FileName:@"tmp. PNG"MimeType:@"Image/png"Error:nil]; }} Error:nil];//@ "Image/png" @ "Application/octet-stream" MimeTypeAfurlsessionmanager *manager =[[Afurlsessionmanager alloc] Initwithsessionconfiguration:[nsurlsessionconfiguration Defaultsessionconfiguration]]; Nsprogress*progress =Nil; Nsurlsessionuploadtask*uploadtask = [Manager uploadtaskwithstreamedrequest:request progress:&progress completionhandler:^ ( Nsurlresponse *response,IDResponseobject, Nserror *error) {    if(Error) {MyLog (@"request =%@", request); MyLog (@"response =%@", response); MyLog (@"Error:%@", error);        [_hud Hide:yes]; Cxalertview*alert=[[cxalertview alloc]initwithtitle:nslocalizedstring (@"Warning", nil) message:nslocalizedstring (@"Upload Failed", nil) cancelbuttontitle:nslocalizedstring (@"Iknow", nil)]; Alert.showblurbackground=NO;    [Alert show]; } Else{MyLog (@"%@ %@", response, Responseobject); Nsdictionary*backdict= (Nsdictionary *) Responseobject; if([backdict[@"Success"] Boolvalue]! =NO) {_hud.labeltext= Nslocalizedstring (@"Updating", nil); [Self updateresxdatewithdict:backdict discription:dict[@"discription"]];        [_hud Hide:yes]; }Else{[_hud hide:yes]; [Myhelper showalertwith:nil txt:backdict[@"msg"]]; }} [Progress removeobserver:self Forkeypath:@"fractioncompleted"context:null];}]; [Progress addobserver:self Forkeypath:@"fractioncompleted"Options:nskeyvalueobservingoptionnew Context:null]; [Progress Setuserinfoobject:@"someThing"Forkey:@"y.x."]; [Uploadtask resume];}

To delete a video in a sandbox:

#pragmaMark-Clears the video file in documents-(void) Clearmoviefromdoucments{nsfilemanager*filemanager =[Nsfilemanager Defaultmanager]; Nsarray*paths =nssearchpathfordirectoriesindomains (NSDocumentDirectory, Nsuserdomainmask, YES); NSString*documentsdirectory = [Paths Objectatindex:0]; Nsarray*contents =[FileManager contentsofdirectoryatpath:documentsdirectory error:null]; Nsenumerator*e =[contents Objectenumerator]; NSString*filename; while(filename =[e Nextobject])) {MyLog (@"%@", filename); if([filename isequaltostring:@"tmp. PNG"]) {MyLog (@"Delete%@", filename);        [FileManager removeitematpath:[documentsdirectory Stringbyappendingpathcomponent:filename] Error:NULL]; Continue; }    if([[[FileName pathextension] lowercasestring] isequaltostring:@"mp4"]||[[[FileName pathextension] lowercasestring] isequaltostring:@"mov"]||[[[FileName pathextension] lowercasestring] isequaltostring:@"PNG"]) {MyLog (@"Delete%@", filename);    [FileManager removeitematpath:[documentsdirectory Stringbyappendingpathcomponent:filename] Error:NULL]; }}}

53rd, OC use AFN upload video to the server

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.