视频上传

//注意要给self.imagePicker设置代理
- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex{
     // 判断是否支持相机
        if([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) {
            switch (buttonIndex) {
                case 0:{//拍摄
                    
                    self.imagePicker.sourceType = UIImagePickerControllerSourceTypeCamera;
                    self.imagePicker.view.hidden = NO;
                    self.imagePicker.mediaTypes = @[(NSString *)kUTTypeMovie];
                    self.imagePicker.videoMaximumDuration = 30;
                    [self presentViewController:self.imagePicker animated:YES completion:NULL];
                }
                    break;
                case 1:{//从相册选择视频
                
                    UIImagePickerController *ipc = [[UIImagePickerController alloc] init];
                    if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypePhotoLibrary]){
                        ipc.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
                        ipc.mediaTypes = [UIImagePickerController availableMediaTypesForSourceType:ipc.sourceType];
                        ipc.mediaTypes = [[NSArray alloc] initWithObjects:(NSString*) kUTTypeMovie, (NSString*) kUTTypeVideo, nil];
                        
                    }
                    ipc.delegate = self;
                    ipc.allowsEditing = NO;
                    [self presentViewController:ipc animated:YES completion:NULL];
                }
                    
                    break;
               
                default:
                    break;
                    
            }
        }
}

#pragma mark - UIImagePickerControllerDelegate

- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
    NSString *mediaType = info[UIImagePickerControllerMediaType];
    if ([mediaType isEqualToString:(NSString *)kUTTypeMovie])//视频上传
    {
        NSURL *videoURL = info[UIImagePickerControllerMediaURL];
        __weak typeof(self) weakSelf = self;
        NSLog(@"media %@",info);
        NSURL    *movieURL = [info valueForKey:UIImagePickerControllerMediaURL];
        NSDictionary *opts = [NSDictionary dictionaryWithObject:[NSNumber numberWithBool:NO]
                                                         forKey:AVURLAssetPreferPreciseDurationAndTimingKey];
        
        AVURLAsset *urlAsset = [AVURLAsset URLAssetWithURL:movieURL options:opts];  // 初始化视频媒体文件
        
        long long  second = 0;
        
        second = urlAsset.duration.value / urlAsset.duration.timescale; // 获取视频总时长,单位秒
        
        NSLog(@"movie duration : %lld", second);
        [picker dismissViewControllerAnimated:YES completion:^{
            CGRect frame = weakSelf.view.frame;
            if (frame.size.height == SCREEN_WIDTH - 44) {
                picker.view.hidden = YES;
                [weakSelf presentViewController:picker animated:NO completion:nil];
                [picker dismissViewControllerAnimated:NO completion:nil];
            }
            
        }];
        // video url:
        // file:///private/var/mobile/Applications/B3CDD0B2-2F19-432B-9CFA-158700F4DE8F/tmp/capture-T0x16e39100.tmp.9R8weF/capturedvideo.mp4
        // we will convert it to mp4 format
        NSURL *mp4 = [self convert2Mp4:videoURL];
        NSFileManager *fileman = [NSFileManager defaultManager];
        if ([fileman fileExistsAtPath:videoURL.path]) {
            NSError *error = nil;
            [fileman removeItemAtURL:videoURL error:&error];
            if (error) {
                NSLog(@"failed to remove file, error:%@.", error);
            }
        }
        [self uploadfile:mp4.path];
        
    }else//照片上传
    {
        
        UIImage *orgImage = info[UIImagePickerControllerOriginalImage];
//         2.取出用户选中的图片
        UIImage *image = info[UIImagePickerControllerOriginalImage];
        NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
        [self.imageArray addObject:image];
        _projectView.photoAry = self.imageArray;

        NSDictionary *dict = @{
                               @"type" :@"1",
                               @"access_token":[XHLoginTool token],

                               };

        [XHHttpTool postURlForPicture:YF_UPLOAD paremeter:dict NSMutableArray:self.imageArray
                           goodResult:^(id responseObj) {
                               XHLog(@"postURlForPicture =%@",responseObj);
                               self.projectModel.ImageId = responseObj;

                           } badResult:^(NSError *error) {
                               XHLog(@"失败");
                           } noNetWork:^{
                               XHLog(@"~~没网了亲~~");
                           } InView:self.view haveProgress:YES];
        
        [picker dismissViewControllerAnimated:YES completion:nil];
    }
}

#pragma mark 网络请求
/**
 *  功能 AFNetWorking带进度指示文件上传
 *  @param filePath 文件路径
 */
-(void)uploadfile:(NSString *)filePath
{
    //服务器所需参数(非必须)
    NSMutableDictionary *params=[NSMutableDictionary dictionary];
    [params setObject:@"0" forKey:@"uptype"];  //0-表单上传  1-字节流上传
    [params setObject:@"VEJQemdPdDd6ZEdhYWY1" forKey:@"key"];
    
    NSData  *fileData=[NSData dataWithContentsOfFile:filePath];  //二进制数据
    NSString *fileName=[filePath lastPathComponent];             //文件名
    NSString *mimeType=@"video/mp4";//[self getMIMEType:filePath];              //文件类型
    
    if (!mimeType) {
        mimeType = @"application/octet-stream";
    }
    NSMutableURLRequest *request = [[AFHTTPRequestSerializer serializer] multipartFormRequestWithMethod:@"POST" URLString:@"http://testfront.vcspark.com/app/projectFiles/upProjectFile" parameters:params constructingBodyWithBlock:^(id<AFMultipartFormData> formData){
        
        [formData appendPartWithFileData:fileData name:@"file" fileName:fileName mimeType:mimeType];
    } error:nil];
    
    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) {
            NSLog(@"Error: %@", error);
        } else {
            NSLog(@"response:%@ ,responseObject%@", response, responseObject);
        }
    }];
    
    [uploadTask resume];
}

- (NSURL *)convert2Mp4:(NSURL *)movUrl {
    NSURL *mp4Url = nil;
    AVURLAsset *avAsset = [AVURLAsset URLAssetWithURL:movUrl options:nil];
    NSArray *compatiblePresets = [AVAssetExportSession exportPresetsCompatibleWithAsset:avAsset];
    
    if ([compatiblePresets containsObject:AVAssetExportPresetHighestQuality]) {
        AVAssetExportSession *exportSession = [[AVAssetExportSession alloc]
                                               initWithAsset:avAsset
                                               presetName:AVAssetExportPreset640x480];
        mp4Url = [movUrl copy];
        mp4Url = [mp4Url URLByDeletingPathExtension];
        mp4Url = [mp4Url URLByAppendingPathExtension:@"mp4"];
        exportSession.outputURL = mp4Url;
        exportSession.shouldOptimizeForNetworkUse = YES;
        exportSession.outputFileType = AVFileTypeMPEG4;
        dispatch_semaphore_t wait = dispatch_semaphore_create(0l);
        //        [self showHudInView:self.view hint:@"正在压缩"];
        //        __weak typeof(self) weakSelf = self;
        [exportSession exportAsynchronouslyWithCompletionHandler:^{
            //            [weakSelf hideHud];
            switch ([exportSession status]) {
                case AVAssetExportSessionStatusFailed: {
                    NSLog(@"failed, error:%@.", exportSession.error);
                } break;
                case AVAssetExportSessionStatusCancelled: {
                    NSLog(@"cancelled.");
                } break;
                case AVAssetExportSessionStatusCompleted: {
                    NSLog(@"completed.");
                } break;
                default: {
                    NSLog(@"others.");
                } break;
            }
            dispatch_semaphore_signal(wait);
        }];
        long timeout = dispatch_semaphore_wait(wait, DISPATCH_TIME_FOREVER);
        if (timeout) {
            NSLog(@"timeout.");
        }
        if (wait) {
            //dispatch_release(wait);
            wait = nil;
        }
    }
    
    return mp4Url;
}


你可能感兴趣的:(视频上传)