栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 移动开发 > iOS

iOS 使用AFN上传视频到服务器示例代码

iOS 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

iOS 使用AFN上传视频到服务器示例代码

这里介绍用AFN上传本地拍摄的视频到服务端。

整体思路:拿到视频资源,先转为mp4,写进沙盒,然后上传,上传成功后要记得删除沙盒中的文件。

压缩导出视频

//视频转换为MP4
//转码操作...
_hud.mode = MBProgressHUDModeIndeterminate;
_hud.labelText = @"转码中...";
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---转换成功");
      _filePath = _outfilePath;
      _filePathURL = [NSURL URLWithString:[NSString stringWithFormat:@"file://%@",_outfilePath]];
MyLog(@"转换完成_filePath = %@\n_filePathURL = %@",_filePath,_filePathURL);
      //获取大小和长度
      [self SetViewText];
      [self uploadNetWorkWithParam:@{@"contenttype":@"application/octet-stream",@"discription":description}];
    }else{
      MyLog(@"转换失败,值为:%li,可能的原因:%@",(long)[exportSession status],[[exportSession error] localizedDescription]);
      [_hud hide:YES];
      [MyHelper showalertWith:nil txt:@"转换失败,请重试"];
    }
  }];
}

开始上传

- (void)uploadNetWorkWithParam:(NSDictionary*)dict {
  MyLog(@"开始上传_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":dict[@"discription"],@"isimage":@(_isImage)}
constructingBodyWithBlock:^(id 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" mimeType
  AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
  NSProgress *progress = nil;
  NSURLSessionUploadTask *uploadTask = [manager uploadTaskWithStreamedRequest:request progress:&progress completionHandler:^(NSURLResponse *response, id responseObject, 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];
}

清除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(@"删除%@",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(@"删除%@",filename);
      [fileManager removeItemAtPath:[documentsDirectory stringByAppendingPathComponent:filename] error:NULL];
    }
  }
}

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持考高分网。

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/166639.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号