服务器之家

服务器之家 > 正文

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

时间:2021-03-13 16:41     来源/作者:Mint丶bin

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

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

压缩导出视频

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
//视频转换为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:@"转换失败,请重试"];
    }
  }];
}

开始上传

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
- (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中视频

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
-(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];
    }
  }
}

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

原文链接:http://www.jianshu.com/p/c61c25befa8b

标签:

相关文章

热门资讯

2020微信伤感网名听哭了 让对方看到心疼的伤感网名大全
2020微信伤感网名听哭了 让对方看到心疼的伤感网名大全 2019-12-26
yue是什么意思 网络流行语yue了是什么梗
yue是什么意思 网络流行语yue了是什么梗 2020-10-11
背刺什么意思 网络词语背刺是什么梗
背刺什么意思 网络词语背刺是什么梗 2020-05-22
Intellij idea2020永久破解,亲测可用!!!
Intellij idea2020永久破解,亲测可用!!! 2020-07-29
苹果12mini价格表官网报价 iPhone12mini全版本价格汇总
苹果12mini价格表官网报价 iPhone12mini全版本价格汇总 2020-11-13
返回顶部