从相册选择照片或者视频,拍照片或者视频上传

//
// AddImageRecordingViewController.m
// WXFPTP
//
// Created by apple on 16/9/28.
// Copyright © 2016年 apple. All rights reserved.
//

import "AddImageRecordingViewController.h"

import "Header.h"

import "PictureCollectionViewCell.h"

import "PictureAddCell.h"

import "InterviewReusableView.h"

import

import "ShootVideoViewController.h"

import "AVViewController.h"

import "ALAsset+mExport.h"

import "AddInterModel.h"

import "LookModel.h"

// caches路径

define KCachesPath \

[NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) objectAtIndex:0]

typedef void(^finishTranscodingBlock)(NSURL*fileURL);

@interface AddImageRecordingViewController (){

NetWorkTools *netWork;
UIImagePickerController *imagePicker;
AddInterModel *addModel;
LookModel *lookModel;
//请求的次数
NSInteger index;
//是否上传成功
BOOL isUpLoadSuccess;
//选中的照片
id selectImg;
// 加号图片
UIImage *addImg;

}

@property (nonatomic,strong) CustomNavigation *custom;
@property (nonatomic,strong) UIScrollView *scrollView;
@property (nonatomic,strong) NSMutableArray *dataArray;
@property (nonatomic,strong) UIView backView;
/
信息 */
@property (nonatomic,strong) UILabel *nameLabel;
@property (nonatomic,strong) UILabel *resonLabel;
@property (nonatomic,strong) UILabel addressLabel;
/
collectionView 数组 */
@property (nonatomic,strong) UICollectionView *pictureCollectonView;
@property(nonatomic,strong)NSMutableArray *itemsSectionPictureArray1;
@property(nonatomic,strong)NSMutableArray *itemsSectionPictureArray2;
@property(nonatomic,strong)NSMutableArray *itemsSectionPictureArray3;

@property (nonatomic,strong) NSArray >lookArray;

/* 放大 */
@property (nonatomic,strong) UIView *fangdaView;
@property (nonatomic,strong) UIImageView *fangdaImage;

//选中
@property(nonatomic,assign)NSInteger selectSectionIndex;
//标题
@property(nonatomic,copy)NSArray *titleArray;
//播放
@property(nonatomic,strong)AVPlayer *player;
@property(nonatomic,strong)AVPlayerLayer *layer;

@end

@implementation AddImageRecordingViewController

static NSString *imgID = @"PictureCollectionViewCellImg";
static NSString *MP4ID = @"PictureCollectionViewCellMP4";
static NSString *nibNmae = @"PictureCollectionViewCell";
static NSString *imageServerUrl = @"http://221.204.177.89:8080";
static NSString *imageLocalUrl = @"http://192.168.1.22:8080";

  • (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.

    _titleArray=@[@"贫困现状:",@"扶贫过程:",@"脱贫:"];
    netWork = [NetWorkTools shareNetWorkTools];
    isUpLoadSuccess = NO;

    self.dataArray = [[NSMutableArray alloc] init];
    self.itemsSectionPictureArray1=[NSMutableArray array];
    self.itemsSectionPictureArray2=[NSMutableArray array];
    self.itemsSectionPictureArray3=[NSMutableArray array];

    addImg = [UIImage imageNamed:@"添加"];

    self.view.backgroundColor = [UIColor whiteColor];
    self.selectSectionIndex = -1;
    //创建导航栏
    [self createNavigation];
    //创建scrollerView
    [self createScrollView];
    //创建数据源
    [self createDataSource];
    //查看图片或者视频
    [self createLookDataSource];
    //创建户主
    [self createHuzhu];
    //创建照片
    [self createPicture];
    //上传
    [self createDownload];
    }

pragma mark -- 上传

-(void)createDownload{

UIButton *downloadBtn = [UIButton createButtonFrame:CGRectMake(0, SCREENHEIGHT - 85, SCREENWIDTH, 40) WithTitle:@"上传" AndWithTitleColor:[UIColor blackColor] AndWithBackGroundColor:[UIColor colorWithRed:0.60f green:0.60f blue:0.60f alpha:1.00f] AndWithTarget:self AndWithSelector:@selector(downloadPicture:)];
downloadBtn.titleLabel.font = [UIFont systemFontOfSize:17];
downloadBtn.titleLabel.textAlignment = NSTextAlignmentCenter;
[self.view addSubview:downloadBtn];

}

-(void)downloadPicture:(UIButton *)btn{

NSDictionary *imgParams = nil;
NSDictionary *MP4Params = nil;
NSString *arrStr;
index = 0;

for (int i = 0; i < self.lookArray.count; i++) {
    NSMutableArray *imgArr = [NSMutableArray array];
    NSMutableArray *mp4Arr = [NSMutableArray array];
    for (int j = 0; j < [self.lookArray[i] count]; j++) {
        id obj = self.lookArray[i][j];
        if ([obj isKindOfClass:[UIImage class]]){
            [imgArr addObject:obj];
            //贫困现状--1,视频是6
        }else if ([obj isKindOfClass:[NSURL class]]){
            [mp4Arr addObject:obj];
            //图片是1,视频是6
        }
    }
    if (imgArr.count > 1) {
        arrStr = [self handelArray:imgArr];
        imgParams = @{@"base":arrStr,@"id":self.IDStr,@"flags":[NSString stringWithFormat:@"%d",i+1]};
        if (!arrStr) {
            continue;
        }
        [self ImageArrayLoadWithParams:imgParams];
    }
    if (mp4Arr.count) {
        arrStr = [self handelArray:mp4Arr];
        MP4Params = @{@"base":arrStr,@"id":self.IDStr,@"flags":@"6"};
        if (!arrStr) {
            continue;
        }
        [self MP4ArrayLoadWithParams:MP4Params];
    }
}

}
//处理数组

  • (NSString *)handelArray:(NSArray *)array
    {
    NSMutableArray *tempArr = [NSMutableArray arrayWithCapacity:array.count];

    for (int i=0; i id obj = array[i];
    if ([obj isKindOfClass:[UIImage class]]){
    if (obj == addImg) continue;
    //照片
    NSData *data = UIImageJPEGRepresentation(obj, 0.5f);
    NSString *encodeImgStr = [data base64EncodedStringWithOptions:NSDataBase64Encoding64CharacterLineLength];
    [tempArr addObject:encodeImgStr];
    }else if ([obj isKindOfClass:[NSURL class]]){
    //视频
    NSData *videoData = [NSData dataWithContentsOfURL:obj];
    NSString *encodeMP4Str = [videoData base64EncodedStringWithOptions:NSDataBase64Encoding64CharacterLineLength];
    [tempArr addObject:encodeMP4Str];
    }
    }
    NSString arrStr = [tempArr componentsJoinedByString:@";"];
    return arrStr;
    }
    //上传视频
    -(void)MP4ArrayLoadWithParams:(NSDictionary
    )params
    {
    [netWork POST:PLAYURL parameters:params constructingBodyWithBlock:^(id _Nonnull formData) {

      [formData appendPartWithFileURL:[NSURL URLWithString:PLAYURL] name:@"text.mp4" error:nil];
    

    } progress:^(NSProgress * _Nonnull uploadProgress) {

    } success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) {
    index ++;
    if ([responseObject[@"message"] isEqualToString:@"上传成功"]) {
    isUpLoadSuccess = YES;
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"提示" message:@"上传成功" preferredStyle:UIAlertControllerStyleAlert];
    [self presentViewController:alert animated:YES completion:nil];
    UIAlertAction *certainAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:nil];
    [alert addAction:certainAction];
    }else{
    isUpLoadSuccess = NO;
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"提示" message:@"上传失败" preferredStyle:UIAlertControllerStyleAlert];
    [self presentViewController:alert animated:YES completion:nil];
    UIAlertAction *certainAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:nil];
    [alert addAction:certainAction];
    }

      NSLog(@"Success: %@", responseObject);
    

    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {

    }];
    }
    //上传图片
    -(void)ImageArrayLoadWithParams:(NSDictionary*)params
    {
    [netWork POST:INTERVIEW_UPDOWNLOADURL parameters:params constructingBodyWithBlock:^(id _Nonnull formData) {

      [formData appendPartWithFileURL:[NSURL URLWithString:INTERVIEW_UPDOWNLOADURL] name:@"text.png" error:nil];
    

    } progress:^(NSProgress * _Nonnull uploadProgress) {

    } success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) {
    index ++;
    if ([responseObject[@"message"] isEqualToString:@"上传成功"]) {
    isUpLoadSuccess = YES;
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"提示" message:@"上传成功" preferredStyle:UIAlertControllerStyleAlert];
    [self presentViewController:alert animated:YES completion:nil];
    UIAlertAction *certainAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:nil];
    [alert addAction:certainAction];
    }else{
    isUpLoadSuccess = NO;
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"提示" message:@"上传失败" preferredStyle:UIAlertControllerStyleAlert];
    [self presentViewController:alert animated:YES completion:nil];
    UIAlertAction *certainAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:nil];
    [alert addAction:certainAction];
    }

      NSLog(@"Success: %@", responseObject);
    

    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {

    }];
    }

pragma mark -- 创建照片

-(void)createPicture{

UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc]init];
layout.itemSize = CGSizeMake(75, 75);
layout.minimumInteritemSpacing = 0;
layout.minimumLineSpacing = 5; //上下的间距 可以设置0看下效果
layout.sectionInset = UIEdgeInsetsMake(0.f, 5, 5.f, 5);

//创建 UICollectionView
self.pictureCollectonView = [[UICollectionView alloc] initWithFrame:CGRectMake(0, self.backView.bottom + 5, self.view.w,  SCREENHEIGHT - self.backView.bottom - 40 - 49) collectionViewLayout:layout];

[self.pictureCollectonView registerNib:[UINib nibWithNibName:nibNmae bundle:nil] forCellWithReuseIdentifier:imgID];
[self.pictureCollectonView registerNib:[UINib nibWithNibName:nibNmae bundle:nil] forCellWithReuseIdentifier:MP4ID];

[self.pictureCollectonView registerClass:[InterviewReusableView class] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"ReusableView"];

self.pictureCollectonView.backgroundColor = [UIColor whiteColor];
self.pictureCollectonView.delegate = self;
self.pictureCollectonView.dataSource = self;
[self.scrollView addSubview:self.pictureCollectonView];

CGFloat contentHeight = self.pictureCollectonView.bottom >= SCREENHEIGHT ? self.pictureCollectonView.bottom : SCREENHEIGHT ;
self.scrollView.contentSize = CGSizeMake(SCREENWIDTH, contentHeight + 100);

}

pragma mark collectionViewDelegate

-(NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView
{
//section数量
return 3;
}

  • (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
    {
    //数据数量
    return [self.lookArray[section] count];
    }
  • (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
    {
    //此处就是自定义好的cell
    PictureCollectionViewCell *cell = [self handleCellwithIndexPath:indexPath withCollectionView:collectionView];
    return cell;
    }
    -(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
    {
    self.selectSectionIndex = indexPath.section;
    selectImg = nil;
    [self clickCellWithIndexPath:indexPath];
    }

pragma mark - 点击cell

  • (void)clickCellWithIndexPath:(NSIndexPath *)indexPath
    {
    id data = self.lookArray[indexPath.section][indexPath.row];
    if ([data isKindOfClass:[LookModel class]]) {
    LookModel *model = (LookModel *)data;
    // 后台数据
    BOOL result = [model.fileName hasSuffix:@"mp4"];
    if (result) {
    // 视频
    NSString *medioPath = [NSString stringWithFormat:@"%@%@",imageLocalUrl,model.filePath];
    AVViewController *VC = [[AVViewController alloc]init];
    VC.videoURL = [NSURL URLWithString:medioPath];
    [self.navigationController pushViewController:VC animated:YES];
    }else{
    // 照片
    NSString *imgPath = [NSString stringWithFormat:@"%@%@",imageLocalUrl,model.filePath];
    selectImg = imgPath;
    [self selectPhoto];
    }
    }else{
    // 选择的数据
    if ([data isKindOfClass:[NSURL class]]) {
    NSLog(@"1111----视频");
    AVViewController *VC = [[AVViewController alloc]init];
    VC.videoURL = (NSURL *)data;
    [self.navigationController pushViewController:VC animated:YES];
    }else{

          NSData *resultData = UIImagePNGRepresentation((UIImage *)data);
          NSData *addData = UIImagePNGRepresentation(addImg);
          if ([resultData isEqual:addData]) {
              // 点击了加号
              [self selectPhoto];
          }
          selectImg = (UIImage *)data;
      }
    

    }
    }

pragma mark - 处理cell

  • (PictureCollectionViewCell *)handleCellwithIndexPath:(NSIndexPath *)indexPath withCollectionView:(UICollectionView *)collectionView
    {
    PictureCollectionViewCell *cell;
    id data = self.lookArray[indexPath.section][indexPath.row];
    cell.removeBtn.hidden = NO;
    if ([data isKindOfClass:[LookModel class]]) {
    LookModel *model = (LookModel *)data;
    // 后台加载的数据
    BOOL result = [model.fileName hasSuffix:@"mp4"];
    if (result) {
    // 视频
    NSString *medioPath = [NSString stringWithFormat:@"%@%@",imageLocalUrl,model.filePath];
    cell = [collectionView dequeueReusableCellWithReuseIdentifier:MP4ID forIndexPath:indexPath];
    AVPlayer *player = [AVPlayer playerWithURL:[NSURL URLWithString:medioPath]];
    // 4.添加AVPlayerLayer
    AVPlayerLayer *layer = [AVPlayerLayer playerLayerWithPlayer: player];
    layer.frame = cell.imageView.bounds;
    [cell.imageView.layer addSublayer:layer];

      }else{
          // 照片
          NSString *imgPath = [NSString stringWithFormat:@"%@%@",imageLocalUrl,model.filePath];
          cell = [collectionView dequeueReusableCellWithReuseIdentifier:imgID forIndexPath:indexPath];
          [cell.imageView setImageWithURL: [NSURL URLWithString:imgPath]];
      }
    

    }else{
    // 选择的数据
    if ([data isKindOfClass:[UIImage class]]) {
    cell = [collectionView dequeueReusableCellWithReuseIdentifier:imgID forIndexPath:indexPath];
    cell.imageView.image = (UIImage *)data;
    cell.removeBtn.hidden = NO;
    NSData *resultData = UIImagePNGRepresentation((UIImage *)data);
    NSData *addData = UIImagePNGRepresentation(addImg);
    if ([resultData isEqual:addData]) {
    cell.removeBtn.hidden = YES;
    }

      }else{
          cell = [collectionView dequeueReusableCellWithReuseIdentifier:MP4ID forIndexPath:indexPath];
          cell.removeBtn.hidden = NO;
          self.player = [AVPlayer playerWithURL:(NSURL *)data];
          // 4.添加AVPlayerLayer
          AVPlayerLayer *layer = [AVPlayerLayer playerLayerWithPlayer:_player];
          self.layer = layer;
          [self.layer player];
          layer.frame = cell.imageView.bounds;
          [cell.imageView.layer addSublayer:layer];
      }
    

    }
    // 删除按钮
    cell.cellIndexPath = indexPath;
    __weak typeof(self)weakSelf=self;
    [cell setCellBtnClick:^(NSIndexPath *selectIndex){
    NSLog(@"---点击了删除按钮");
    if ([data isKindOfClass:[LookModel class]]) {
    // 调后台数据
    NSLog(@"删除后台数据");
    [weakSelf createRemoveDataSource:(LookModel *)data withIndex:indexPath];
    }else{
    // 直接删除对应位置的数据
    [weakSelf.lookArray[selectIndex.section] removeObjectAtIndex: selectIndex.row];
    [weakSelf.pictureCollectonView reloadSections:[NSIndexSet indexSetWithIndex:weakSelf.selectSectionIndex]];
    }
    }];

    return cell;
    }

  • (void)selectPhoto
    {
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"添加照片" message:nil preferredStyle:UIAlertControllerStyleActionSheet];
    [alert addAction:[UIAlertAction actionWithTitle:@"打开照相机" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action){
    //选择照相机
    [self takePhoto];
    }]];
    [alert addAction:[UIAlertAction actionWithTitle:@"从相册选择" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
    //选择相册
    [self LocalPhoto];
    }]];
    if (self.selectSectionIndex == 0) {
    [alert addAction:[UIAlertAction actionWithTitle:@"拍摄视频" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
    //视频
    [self ShootVideo];
    }]];
    }
    [alert addAction:[UIAlertAction actionWithTitle:@"查看大图" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
    //查看大图
    [self LookBigImage:selectImg];
    }]];
    [alert addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil]];
    [self presentViewController:alert animated:YES completion:nil];
    }

pragma mark -- 照相机

  • (void)takePhoto
    {
    UIImagePickerControllerSourceType sourcType = UIImagePickerControllerSourceTypeCamera;
    if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) {
    imagePicker = [[UIImagePickerController alloc]init];
    imagePicker.delegate = self;
    imagePicker.sourceType = sourcType;
    [self presentViewController:imagePicker animated:YES completion:nil];

    }else{
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"提示" message:nil preferredStyle:UIAlertControllerStyleActionSheet];
    [alert addAction:[UIAlertAction actionWithTitle:@"无法调取相机,请检查" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {

      }]];
      [alert addAction:[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleCancel handler:nil]];
      [self presentViewController:alert animated:YES completion:nil];
      return;
    

    }
    }

pragma mark - 照片选择代理方法

  • (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
    {
    NSString *mediaType=[info objectForKey:UIImagePickerControllerMediaType];
    if ([mediaType isEqualToString:(NSString *)kUTTypeImage]) {//如果是拍照
    UIImage *image;
    //如果允许编辑则获得编辑后的照片,否则获取原始照片
    // 1. 获取编辑后的照片
    switch (picker.sourceType) {
    case UIImagePickerControllerSourceTypeCamera:
    image = info[@"UIImagePickerControllerOriginalImage"];

              break;
          case UIImagePickerControllerSourceTypePhotoLibrary:
              image = info[@"UIImagePickerControllerEditedImage"];
              break;
          default:
              break;
      }
      if (image) {
          [self addImage:image];
      }
    

    }
    // 3. 关闭照片选择控制器
    [self dismissViewControllerAnimated:YES completion:nil];
    [self.pictureCollectonView reloadSections:[NSIndexSet indexSetWithIndex:self.selectSectionIndex]];
    }

pragma mark - 添加照片进数组

  • (void)addImage:(id)data
    {
    int i = 0;
    for (UIImage *image in self.lookArray[self.selectSectionIndex]) {
    if (image == addImg) {
    [self.lookArray[self.selectSectionIndex] removeObjectAtIndex:i];
    }
    i ++;
    }
    [self.lookArray[self.selectSectionIndex] addObject:data];
    [self.lookArray[self.selectSectionIndex] addObject:addImg];
    }

pragma mark -- 相册

  • (void)LocalPhoto
    {
    NSInteger maxImageCount = 10;

    maxImageCount -= [self.lookArray[self.selectSectionIndex] count];

    ELCImagePickerController *elcPicker = [[ELCImagePickerController alloc] initImagePicker];
    elcPicker.maximumImagesCount = maxImageCount; //选择图像的最大数量设置为9
    elcPicker.returnsOriginalImage = NO; //只返回fullScreenImage,不是fullResolutionImage
    elcPicker.returnsImage = YES; //如果是的 返回UIimage。如果没有,只返回资产位置信息
    elcPicker.onOrder = YES; //对多个图像选择、显示和返回的顺序选择图像
    // elcPicker.mediaTypes = @[(NSString *)kUTTypeImage]; //支持图片和电影类型
    elcPicker.imagePickerDelegate = self;
    [self presentViewController:elcPicker animated:YES completion:nil];
    }
    //相册

  • (void)elcImagePickerController:(ELCImagePickerController *)picker didFinishPickingMediaWithInfo:(NSArray *)info
    {
    __weak typeof(self)weakSelf=self;
    for (NSDictionary *dict in info) {

      if ([dict objectForKey:UIImagePickerControllerMediaType] == ALAssetTypePhoto){
          if ([dict objectForKey:UIImagePickerControllerOriginalImage]){
              //把图片取出来放到数组里面
              UIImage* image=[dict objectForKey:UIImagePickerControllerOriginalImage];
    

// [self.lookArray[self.selectSectionIndex] addObject:image];
[self addImage:image];
}
}else if ([dict objectForKey:UIImagePickerControllerMediaType] == ALAssetTypeVideo){
if ([dict objectForKey:UIImagePickerControllerReferenceURL]){
//把视频取出来放到数组里面
NSURL *videoUrl =[dict objectForKey:UIImagePickerControllerReferenceURL];
[weakSelf videoWithUrl:videoUrl withFileName:@"videoName.mp4" finish:^(NSURL *filePath) {
[weakSelf addImage:filePath];
NSLog(@"----%@",videoUrl);
dispatch_async(dispatch_get_main_queue(), ^{

                    [weakSelf.pictureCollectonView reloadSections:[NSIndexSet indexSetWithIndex:self.selectSectionIndex]];
                });
            }];
        }
    }
}
[self dismissViewControllerAnimated:YES completion:nil];
[self.pictureCollectonView reloadSections:[NSIndexSet indexSetWithIndex:self.selectSectionIndex]];

}

// MARK: -- 将原始视频的URL转化为NSData数据,写入沙盒

  • (void)videoWithUrl:(NSURL *)url withFileName:(NSString *)fileName finish:(finishTranscodingBlock) finishTranscoding
    {
    // 解析一下,为什么视频不像图片一样一次性开辟本身大小的内存写入?
    // 想想,如果1个视频有1G多,难道直接开辟1G多的空间大小来写?
    ALAssetsLibrary *assetLibrary = [[ALAssetsLibrary alloc] init];
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
    if (url) {
    [assetLibrary assetForURL:url resultBlock:^(ALAsset *asset) {
    ALAssetRepresentation *rep = [asset defaultRepresentation];
    NSString * videoPath = [KCachesPath stringByAppendingPathComponent:fileName];

              if ( [[NSFileManager defaultManager] fileExistsAtPath:videoPath]) {
                  
                  [[NSFileManager defaultManager] removeItemAtPath:videoPath error:nil];
              }
              char const *cvideoPath = [videoPath UTF8String];
              FILE *file = fopen(cvideoPath, "a+");
              if (file) {
                  const int bufferSize = 1024 * 1024;
                  // 初始化一个1M的buffer
                  Byte *buffer = (Byte*)malloc(bufferSize);
                  NSUInteger read = 0, offset = 0, written = 0;
                  NSError* err = nil;
                  if (rep.size != 0)
                  {
                      do {
                          read = [rep getBytes:buffer fromOffset:offset length:bufferSize error:&err];
                          written = fwrite(buffer, sizeof(char), read, file);
                          offset += read;
                      } while (read != 0 && !err);//没到结尾,没出错,ok继续
                  }
                  // 释放缓冲区,关闭文件
                  free(buffer);
                  buffer = NULL;
                  fclose(file);
                  file = NULL;
                  
                  finishTranscoding([NSURL fileURLWithPath:videoPath]);
              }
          } failureBlock:nil];
      }
    

    });
    }
    -(void)elcImagePickerControllerDidCancel:(ELCImagePickerController *)picker{
    NSLog(@"取消");

    [self dismissViewControllerAnimated:YES completion:nil];
    }

  • (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath
    {
    InterviewReusableView *headReusableView;
    //此处是headerView
    if (kind == UICollectionElementKindSectionHeader) {
    headReusableView = [collectionView dequeueReusableSupplementaryViewOfKind:kind withReuseIdentifier:@"ReusableView" forIndexPath:indexPath];

      UILabel *titLeLab=nil;
      for (UIView *view in [headReusableView subviews]) {
          if ([view isKindOfClass:[UILabel class]]) {
              titLeLab=(UILabel *)view;
          }
      }
      if (!titLeLab) {
          titLeLab=[[UILabel alloc]initWithFrame:headReusableView.bounds];
      }
      [headReusableView addSubview:titLeLab];
      
      titLeLab.text = self.titleArray[indexPath.section];
    

    }
    return headReusableView;
    }
    //执行的 headerView 代理 返回 headerView 的高度

  • (CGSize)collectionView:(UICollectionView )collectionView layout:(UICollectionViewLayout)collectionViewLayout referenceSizeForHeaderInSection:(NSInteger)section
    {
    return CGSizeMake(SCREENWIDTH, 30);
    }

pragma mark -- 拍视频

-(void)ShootVideo{

NSLog(@"录制视频");
ShootVideoViewController *vc = [[ShootVideoViewController alloc]init];
vc.finshBlock = ^(NSURL *url){
    if (!url) {
        return ;
    }
    [self.lookArray[self.selectSectionIndex] addObject:url];
    [self.pictureCollectonView reloadSections:[NSIndexSet indexSetWithIndex:self.selectSectionIndex]];
};
[self.navigationController pushViewController:vc animated:YES];

}

pragma mark -- 查看大图

-(void)LookBigImage:(id)image{

if (!image)return;
self.fangdaView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, SCREENWIDTH, SCREENHEIGHT)];
[self.fangdaView setBackgroundColor:[UIColor blackColor]];
[self.view addSubview:self.fangdaView];
//创建显示图像的视图
self.fangdaImage = [[UIImageView alloc] initWithFrame:CGRectMake(0, SCREENHEIGHT / 2 - 200, SCREENWIDTH, 300)];
//要显示的图片,即要放大的图片
[self.fangdaView addSubview:self.fangdaImage];
self.fangdaImage.userInteractionEnabled = YES;
//添加点击手势(即点击图片后退出全屏)
UITapGestureRecognizer *tapGesture = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(closeView)];
[self.fangdaImage addGestureRecognizer:tapGesture];
if ([image isKindOfClass:[UIImage class]]) {
    self.fangdaImage.image = image;
}else{
    [self.fangdaImage setImageWithURL:[NSURL URLWithString:(NSString *)image]];
}

}

-(void)closeView{
[self.fangdaView removeFromSuperview];
}

pragma mark -- 创建户主

-(void)createHuzhu{

self.backView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREENWIDTH, 70)];
// self.backView.backgroundColor = [UIColor cyanColor];
[self.scrollView addSubview:self.backView];

//户主姓名
self.nameLabel = [UILabel createLabelFrame:CGRectMake(5, 5, (SCREENWIDTH - 10) / 2, 30) withText:@"户主姓名:" AndWithFont:[UIFont systemFontOfSize:16] AndWithTextColor:nil AndWithBackgroundColor:[UIColor whiteColor] AndWithTextAlignment:NSTextAlignmentLeft];
[self.backView addSubview:self.nameLabel];

//家庭人口
self.resonLabel = [UILabel createLabelFrame:CGRectMake(self.nameLabel.right + 10, 5, self.nameLabel.w, 30) withText:@"致贫原因:" AndWithFont:[UIFont systemFontOfSize:16] AndWithTextColor:nil AndWithBackgroundColor:[UIColor whiteColor] AndWithTextAlignment:NSTextAlignmentLeft];
[self.backView addSubview:self.resonLabel];

//家庭住址
self.addressLabel = [UILabel createLabelFrame:CGRectMake(5, self.nameLabel.bottom + 5, SCREENWIDTH, 30) withText:@"家庭住址:" AndWithFont:[UIFont systemFontOfSize:16] AndWithTextColor:nil AndWithBackgroundColor:[UIColor whiteColor] AndWithTextAlignment:NSTextAlignmentLeft];
[self.backView addSubview:self.addressLabel];

}

pragma mark -- 创建数据源

-(void)createDataSource{

NSDictionary *params = @{@"id":self.IDStr};

[SVProgressHUD show];
[netWork loadDataWithURL:ADDINTERVIEW_URL andParams:params requestType:Get finfishBlock:^(id result, NSError *error) {
    if (!error) {
        [SVProgressHUD dismiss];
        [self.dataArray removeAllObjects];
        
        for (NSDictionary *dic in result[@"rows"]) {
            
            addModel = [AddInterModel AddInterModelWithDict:dic];
            addModel.Id = dic[@"id"];
            [self.dataArray addObject:addModel];
        }
        self.nameLabel.text = [NSString stringWithFormat:@"户主姓名:%@",addModel.huzhu];
        self.resonLabel.text = [NSString stringWithFormat:@"致贫原因:%@",addModel.yuanyin];
        self.addressLabel.text = [NSString stringWithFormat:@"家庭地址:%@",addModel.dizhi];
    }else{
        [SVProgressHUD showErrorWithStatus:@"加载失败..." duration:1.0];
        NSLog(@"errorerror===%@",error);
    }
}];

}

pragma mark - 清除数据

  • (void)clearData
    {
    // [self.lookArray removeAllObjects];
    [self.itemsSectionPictureArray1 removeAllObjects];
    [self.itemsSectionPictureArray2 removeAllObjects];
    [self.itemsSectionPictureArray3 removeAllObjects];
    }
    // MARK: -- 查看图片或者视频
    -(void)createLookDataSource{

    NSDictionary *params = @{@"id":self.IDStr};

    [[NetWorkTools shareNetWorkTools] loadDataWithURL:LOOK_URL andParams:params requestType:Post finfishBlock:^(id result, NSError *error) {
    if (!error) {
    NSMutableArray *arrM = [NSMutableArray arrayWithCapacity:3];
    [self clearData];
    for (NSDictionary *dic in result[@"rows"]) {
    lookModel = [LookModel LookModelWithDict:dic];
    if ([lookModel.flg isEqualToString:@"2"]) {
    [self.itemsSectionPictureArray2 addObject:lookModel];
    }else if ([lookModel.flg isEqualToString:@"3"]){
    [self.itemsSectionPictureArray3 addObject:lookModel];
    }else if ([lookModel.flg isEqualToString:@"1"] || [lookModel.flg isEqualToString:@"6"]){
    [self.itemsSectionPictureArray1 addObject:lookModel];
    }
    }
    if (!self.itemsSectionPictureArray1.count) {
    [self.itemsSectionPictureArray1 addObject:addImg];
    }
    if (!self.itemsSectionPictureArray2.count) {
    [self.itemsSectionPictureArray2 addObject:addImg];
    }
    if (!self.itemsSectionPictureArray3.count) {
    [self.itemsSectionPictureArray3 addObject:addImg];
    }
    [arrM addObject:self.itemsSectionPictureArray1];
    [arrM addObject:self.itemsSectionPictureArray2];
    [arrM addObject:self.itemsSectionPictureArray3];
    self.lookArray = arrM.copy;
    // 就这里使用全局刷新
    [self.pictureCollectonView reloadData];
    }else{
    NSLog(@"errorerror===%@",error);
    }
    }];
    }

// MARK: -- 删除图片或者视频
-(void)createRemoveDataSource:(LookModel *)model withIndex:(NSIndexPath *)indexPath{

//id -- 如果是删除图片就传图片id,如果是删除视频就传视频id,flag根据查看的flg传
NSLog(@"xiaoxiao----%@",model.removeParams);
[[NetWorkTools shareNetWorkTools] loadDataWithURL:REMOVE_URL andParams:model.removeParams requestType:Post finfishBlock:^(id result, NSError *error) {
    if (!error) {
        if ([result[@"message"] isEqualToString:@"删除成功"]) {
            
            [self.lookArray[indexPath.section] removeObjectAtIndex:indexPath.row];
            if (![self.lookArray[indexPath.section] count]) {
                //删完了
                [self.lookArray[indexPath.section] addObject:addImg];
            }
            [self.pictureCollectonView reloadSections:[NSIndexSet indexSetWithIndex:indexPath.section]];
        }else{
            UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"提示" message:@"删除失败" preferredStyle:UIAlertControllerStyleAlert];
            [self presentViewController:alert animated:YES completion:nil];
            UIAlertAction *certainAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:nil];
            [alert addAction:certainAction];
        }
        NSLog(@"删除--%@",result);
        
    }else{
        
        NSLog(@"errorerror===%@",error);
    }
}];

}

pragma mark --UIScrollView

-(void)createScrollView{
// 1.创建UIScrollView
self.scrollView = [[UIScrollView alloc] init];
self.scrollView.frame = CGRectMake(0, self.custom.h, SCREENWIDTH, SCREENHEIGHT - 64);
// 隐藏水平滚动条
self.scrollView.showsHorizontalScrollIndicator = YES;
self.scrollView.showsVerticalScrollIndicator = YES;
[self.view addSubview:self.scrollView];
}

pragma mark -- 创建导航栏

-(void)createNavigation{

self.custom = [[CustomNavigation alloc] initWithFrame:CGRectMake(0, 0, SCREENWIDTH, 64)];
self.custom.titleLabel.text = @"影像拍摄";
[self.custom.backBtn addTarget:self action:@selector(backPop:) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:self.custom];

}
-(void)backPop:(UIButton *)btn{

[self.navigationController popViewControllerAnimated:YES];
[SVProgressHUD dismiss];

}

@end

你可能感兴趣的:(从相册选择照片或者视频,拍照片或者视频上传)