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

 更新时间:2017年04月17日 15:16:09   作者:Mint丶bin  
本篇文章主要介绍了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<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" 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];
    }
  }
}

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

相关文章

  • safari调试iOS app web页面的步骤

    safari调试iOS app web页面的步骤

    这篇文章主要为大家详细介绍了safari调试iOS app web页面的步骤,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
    2017-06-06
  • IOS开发中键盘输入屏幕上移的解决方法

    IOS开发中键盘输入屏幕上移的解决方法

    在IOS开法中经常会遇到键盘遮挡屏幕的事情,经常档住下面的按钮,下面小编给大家分享IOS开发中键盘输入屏幕上移的解决方法,感兴趣的朋友一起看看吧
    2016-10-10
  • iOS开发中音频工具类的封装以及音乐播放器的细节控制

    iOS开发中音频工具类的封装以及音乐播放器的细节控制

    这篇文章主要介绍了iOS开发中音频工具类的封装以及音乐播放器的细节控制,代码基于传统的Objective-C,需要的朋友可以参考下
    2015-12-12
  • iOS 对当前webView进行截屏的方法

    iOS 对当前webView进行截屏的方法

    下面小编就为大家带来一篇iOS 对当前webView进行截屏的方法。小编觉得挺不错的,现在就分享给大家,也给大家做个参考。一起跟随小编过来看看吧
    2017-04-04
  • iOS如何获取当前日期前后N天的时间示例代码

    iOS如何获取当前日期前后N天的时间示例代码

    这篇文章主要给大家介绍了关于iOS如何获取当前日期前后N天的时间的相关资料,文中通过示例代码介绍的非常详细,对各位iOS开发者们具有一定的参考学习价值,需要的朋友们下面随着小编来一起看看吧。
    2017-11-11
  • iOS指纹识别的简单应用

    iOS指纹识别的简单应用

    这篇文章主要为大家详细介绍了iOS指纹识别的简单应用,文中示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
    2020-07-07
  • 详解iOS使用Keychain中的kSecClassGenericPassword存储数据

    详解iOS使用Keychain中的kSecClassGenericPassword存储数据

    iOS设备中的Keychain是一个安全的存储容器,本篇文章主要介绍了iOS使用Keychain中的kSecClassGenericPassword存储数据,有兴趣的可以了解一下。
    2016-11-11
  • iOS开发之自定义UITextField的方法

    iOS开发之自定义UITextField的方法

    UITextField是IOS开发中用户交互中重要的一个控件,常被用来做账号密码框,输入信息框等。本文给大家介绍iOS开发之自定义UITextField的方法,感兴趣的朋友一起学习吧
    2016-05-05
  • UITableView中Cell重用机制导致内容重复的解决方法

    UITableView中Cell重用机制导致内容重复的解决方法

    这篇文章主要为大家详细介绍了UITableView中Cell重用机制导致内容重复的解决方法,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
    2017-06-06
  • iOS新功能引导提示界面实例详解

    iOS新功能引导提示界面实例详解

    在开发中,现在很多app更新了新功能时都会给出用户一个提示,以方便用户更好的体验,那么这个功能如何实现的呢?下面通过本文给大家分享iOS新功能引导提示界面实例详解,需要的的朋友参考下吧
    2017-04-04

最新评论