// // NewChoiceFileController.m // SiBenClient // // Created by 肖雨 on 2017/9/22. // Copyright © 2017年 ShangLv. All rights reserved. // #import "NewChoiceFileController.h" #import "TZImagePickerController.h" #import "UIView+Layout.h" #import "TZTestCell.h" #import #import #import "LxGridViewFlowLayout.h" #import "TZImageManager.h" #import "TZVideoPlayerController.h" #import "TZPhotoPreviewController.h" #import "TZGifPhotoPreviewController.h" @interface NewChoiceFileController() { NSMutableArray *_selectedPhotos; NSMutableArray *_selectedAssets; } @property (nonatomic,copy) void(^screenAction)(NSString *imagePath); @property (nonatomic, strong) UIImagePickerController *imagePickerVc; @property (nonatomic, weak) UIViewController *controller; @property (nonatomic, copy) NSString *Type; @property (nonatomic, assign) BOOL isSelectOriginalPhoto; @end @implementation NewChoiceFileController - (void)dealloc { //此类根据上级类销毁而销毁 上级界面需要主动销毁此类,复制此段代码 /* - (void)dealloc { 第一步,用willMoveToParentViewController这个方法,并把参数设置为nil,通知VC这个Controller即将被移除父视图控制器。 第二步,把VC.view移除出父视图控制器的view。 第三步,然后用removeFromParentViewcontroller这个方法把VC彻底移除。 if (cont) { [cont willMoveToParentViewController:nil]; [cont.view removeFromSuperview]; [cont removeFromParentViewController]; } } */ NSLog(@"选择文件界面销毁"); } #pragma mark - 上传照片 - (void)startUploadAlbum { if (_selectedPhotos.count <= 0) { [self.controller.view makeToast:@"请添加上传图片" duration:1.0 position:CSToastPositionCenter]; return; }else { [MBProgressHUD showLoadToView:self.controller.view title:@"正在上传,请稍后..."]; } NSMutableArray *imageUploadArray = [NSMutableArray array]; NSString *imagtype; for (int i=0; i<_selectedPhotos.count; i++) { //获取图片名称 NSString *fileName; id asset = _selectedAssets[i]; if ([asset isKindOfClass:[PHAsset class]]) { PHAsset *phAsset = (PHAsset *)asset; fileName = [phAsset valueForKey:@"filename"]; } else if ([asset isKindOfClass:[ALAsset class]]) { ALAsset *alAsset = (ALAsset *)asset; fileName = alAsset.defaultRepresentation.filename; } NSArray *array = [fileName componentsSeparatedByString:@"."]; // if (![[array lastObject] isEqualToString:@"JPG"] && ![[array lastObject] isEqualToString:@"JPEG"] && ![[array lastObject] isEqualToString:@"PNG"]) { // // [MBProgressHUD hideHUDForView:self.view]; // [MBProgressHUD showError:@"暂不支持该图片格式上传" toView:self.view]; // return; // } NSLog(@"正在上传的图片格式为: %@",[array lastObject]); imagtype = [array lastObject]; UIImage *ysImage = _selectedPhotos[i]; NSData *ysImageDataSize = UIImageJPEGRepresentation(ysImage, 1.0); //如果图片大小没有超过500KB 则不进行压缩 if ([ysImageDataSize length]/1000 > 500) { CGSize ysImageSize = ysImage.size; ysImageSize.width *= 0.45; ysImageSize.height *= 0.45; ysImage = [self imageWithImage:ysImage scaledToSize:ysImageSize]; NSData *ysImageData = [NSData dataWithData:UIImageJPEGRepresentation(ysImage,0.7)]; //image=[UIImage imageWithData:imageData]; [imageUploadArray addObject:ysImageData]; NSLog(@"压缩图片大小 = %lu\n 原图大小 = %lu ",[ysImageData length]/1000,[ysImageDataSize length]/1000); }else { [imageUploadArray addObject:ysImageDataSize]; } } NSMutableDictionary *parameters = NewMutableDictionaryInit; NSString *url; NSString *sign; if ([self.Type isEqualToString:@"发布成果"]) { url = JT_uploadPicture; sign = @"achievement_picture"; }else if([self.Type isEqualToString:@"发布需求"]){ url = JT_uploadPicture; sign = @"demand_picture"; }else{ url = JT_uploadImg; } [parameters safeSetObject:sign forKey:@"sign"];//成果 [NetworkRequestManager requestPostWithInterfacePrefix:url serverFileName:@"file" parameters:parameters arrayParameters:imageUploadArray imagetype:imagtype onSuccess:^(id requestData) { [MBProgressHUD hideHUDForView:self.controller.view]; NSLog(@"服务器返回的报文: %@",requestData); if ([self.Type isEqualToString:@"发布成果"]) { [MBProgressHUD showSuccess:@"上传成功" toView:self.view]; }else if([self.Type isEqualToString:@"发布成果"]){ [MBProgressHUD showSuccess:@"上传成功" toView:self.view]; }else{ [MBProgressHUD showSuccess:@"修改头像成功" toView:self.view]; } _screenAction(requestData[@"data"]); } onFailure:^{ [MBProgressHUD hideHUDForView:self.controller.view]; }]; } //后置摄像头情况下 //这时图片的体积在100k左右(iphone5s下,6多了几十k,plus没有真机),1000*几百的分辨率且清晰 -(UIImage*)imageWithImage:(UIImage*)image scaledToSize:(CGSize)newSize { UIGraphicsBeginImageContextWithOptions(newSize, NO, 0.0); [image drawInRect:CGRectMake(0, 0, newSize.width, newSize.height)]; UIImage* scaledImage = UIGraphicsGetImageFromCurrentImageContext(); UIGraphicsEndImageContext(); return scaledImage; } - (void)viewDidLoad { [super viewDidLoad]; // Do any additional setup after loading the view. _selectedPhotos = NewMutableArrayInit; _selectedAssets = NewMutableArrayInit; } #pragma mark - 拍照/相册 - (void)choiceFile:(UIViewController *)controller type:(NSString *)type action:(void(^)(NSString *imagePath))action { self.screenAction = action; self.controller = controller; self.Type = type; [_selectedAssets removeAllObjects]; [_selectedPhotos removeAllObjects]; UIActionSheet *sheet = [[UIActionSheet alloc] initWithTitle:nil delegate:self cancelButtonTitle:@"取消" destructiveButtonTitle:nil otherButtonTitles:@"拍照",@"去相册选择", nil]; [sheet showInView:self.view]; } #pragma mark - UIImagePickerController - (void)takePhoto { AVAuthorizationStatus authStatus = [AVCaptureDevice authorizationStatusForMediaType:AVMediaTypeVideo]; if ((authStatus == AVAuthorizationStatusRestricted || authStatus == AVAuthorizationStatusDenied)) {// && iOS7Later // 无相机权限 做一个友好的提示 UIAlertView * alert = [[UIAlertView alloc]initWithTitle:@"无法使用相机" message:@"请在iPhone的""设置-隐私-相机""中允许访问相机" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"设置", nil]; [alert show]; // 拍照之前还需要检查相册权限 } /* else if ([TZImageManager authorizationStatus] == 2) { // 已被拒绝,没有相册权限,将无法保存拍的照片 UIAlertView * alert = [[UIAlertView alloc]initWithTitle:@"无法访问相册" message:@"请在iPhone的""设置-隐私-相册""中允许访问相册" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"设置", nil]; alert.tag = 1; [alert show]; } */ else { // 调用相机 UIImagePickerControllerSourceType sourceType = UIImagePickerControllerSourceTypeCamera; if ([UIImagePickerController isSourceTypeAvailable: UIImagePickerControllerSourceTypeCamera]) { self.imagePickerVc.sourceType = sourceType; if(iOS8Later) { _imagePickerVc.modalPresentationStyle = UIModalPresentationOverCurrentContext; } [self presentViewController:_imagePickerVc animated:YES completion:nil]; } else { NSLog(@"模拟器中无法打开照相机,请在真机中使用"); } } } - (void)imagePickerController:(UIImagePickerController*)picker didFinishPickingMediaWithInfo:(NSDictionary *)info { [picker dismissViewControllerAnimated:YES completion:nil]; NSString *type = [info objectForKey:UIImagePickerControllerMediaType]; if ([type isEqualToString:@"public.image"]) { TZImagePickerController *tzImagePickerVc = [[TZImagePickerController alloc] initWithMaxImagesCount:1 delegate:self]; tzImagePickerVc.sortAscendingByModificationDate = YES; [tzImagePickerVc showProgressHUD]; UIImage *image = [info objectForKey:UIImagePickerControllerOriginalImage]; // save photo and get asset / 保存图片,获取到asset [[TZImageManager manager] savePhotoWithImage:image completion:^(NSError *error){ if (error) { [tzImagePickerVc hideProgressHUD]; NSLog(@"图片保存失败 %@",error); } else { [[TZImageManager manager] getCameraRollAlbum:NO allowPickingImage:YES completion:^(TZAlbumModel *model) { [[TZImageManager manager] getAssetsFromFetchResult:model.result allowPickingVideo:NO allowPickingImage:YES completion:^(NSArray *models) { [tzImagePickerVc hideProgressHUD]; TZAssetModel *assetModel = [models firstObject]; if (tzImagePickerVc.sortAscendingByModificationDate) { assetModel = [models lastObject]; } [self refreshCollectionViewWithAddedAsset:assetModel.asset image:image]; }]; }]; } }]; } } //拍照之后获得的图片 - (void)refreshCollectionViewWithAddedAsset:(id)asset image:(UIImage *)image { [_selectedAssets addObject:asset]; [_selectedPhotos addObject:image]; [self startUploadAlbum]; } //取消拍照 - (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker { if ([picker isKindOfClass:[UIImagePickerController class]]) { [picker dismissViewControllerAnimated:YES completion:nil]; } } #pragma mark - TZImagePickerController - (void)pushImagePickerController { TZImagePickerController *imagePickerVc = [[TZImagePickerController alloc] initWithMaxImagesCount:1 columnNumber:1 delegate:self pushPhotoPickerVc:YES]; #pragma mark - 四类个性化设置,这些参数都可以不传,此时会走默认设置 imagePickerVc.isSelectOriginalPhoto = _isSelectOriginalPhoto; imagePickerVc.allowTakePicture = NO; // 在内部显示拍照按钮 // 2. Set the appearance // 2. 在这里设置imagePickerVc的外观 // imagePickerVc.navigationBar.barTintColor = [UIColor greenColor]; // imagePickerVc.oKButtonTitleColorDisabled = [UIColor lightGrayColor]; // imagePickerVc.oKButtonTitleColorNormal = [UIColor greenColor]; // imagePickerVc.navigationBar.translucent = NO; // 3. Set allow picking video & photo & originalPhoto or not // 3. 设置是否可以选择视频/图片/原图 imagePickerVc.allowPickingVideo = NO; imagePickerVc.allowPickingImage = YES; imagePickerVc.allowPickingOriginalPhoto = YES; imagePickerVc.allowPickingGif = NO; // 4. 照片排列按修改时间升序 imagePickerVc.sortAscendingByModificationDate = YES; // imagePickerVc.minImagesCount = 3; // imagePickerVc.alwaysEnableDoneBtn = YES; // imagePickerVc.minPhotoWidthSelectable = 3000; // imagePickerVc.minPhotoHeightSelectable = 2000; /// 5. Single selection mode, valid when maxImagesCount = 1 /// 5. 单选模式,maxImagesCount为1时才生效 imagePickerVc.showSelectBtn = NO; imagePickerVc.allowCrop = NO; imagePickerVc.needCircleCrop = NO; imagePickerVc.circleCropRadius = 100; // [imagePickerVc setCropViewSettingBlock:^(UIView *cropView) { // cropView.layer.borderColor = [UIColor redColor].CGColor; // cropView.layer.borderWidth = 2.0; // }]; //imagePickerVc.allowPreview = NO; #pragma mark - 到这里为止 // You can get the photos by block, the same as by delegate. // 你可以通过block或者代理,来得到用户选择的照片. [imagePickerVc setDidFinishPickingPhotosHandle:^(NSArray *photos, NSArray *assets, BOOL isSelectOriginalPhoto) { }]; [self.controller presentViewController:imagePickerVc animated:YES completion:nil]; } #pragma mark - TZImagePickerControllerDelegate /// User click cancel button /// 用户点击了取消 - (void)tz_imagePickerControllerDidCancel:(TZImagePickerController *)picker { NSLog(@"取消选择相册"); } // The picker should dismiss itself; when it dismissed these handle will be called. // If isOriginalPhoto is YES, user picked the original photo. // You can get original photo with asset, by the method [[TZImageManager manager] getOriginalPhotoWithAsset:completion:]. // The UIImage Object in photos default width is 828px, you can set it by photoWidth property. // 这个照片选择器会自己dismiss,当选择器dismiss的时候,会执行下面的代理方法 // 如果isSelectOriginalPhoto为YES,表明用户选择了原图 // 你可以通过一个asset获得原图,通过这个方法:[[TZImageManager manager] getOriginalPhotoWithAsset:completion:] // photos数组里的UIImage对象,默认是828像素宽,你可以通过设置photoWidth属性的值来改变它 - (void)imagePickerController:(TZImagePickerController *)picker didFinishPickingPhotos:(NSArray *)photos sourceAssets:(NSArray *)assets isSelectOriginalPhoto:(BOOL)isSelectOriginalPhoto { _isSelectOriginalPhoto = isSelectOriginalPhoto; // 1.打印图片名字 [self printAssetsName:assets]; [_selectedAssets addObjectsFromArray:assets]; [_selectedPhotos addObjectsFromArray:photos]; [self startUploadAlbum]; } // If user picking a video, this callback will be called. // If system version > iOS8,asset is kind of PHAsset class, else is ALAsset class. // 如果用户选择了一个视频,下面的handle会被执行 // 如果系统版本大于iOS8,asset是PHAsset类的对象,否则是ALAsset类的对象 - (void)imagePickerController:(TZImagePickerController *)picker didFinishPickingVideo:(UIImage *)coverImage sourceAssets:(id)asset { [MBProgressHUD showLoadToView:self.controller.view title:@"请稍后,正在准备上传缓存..."]; // _selectedPhotos = [NSMutableArray arrayWithArray:@[coverImage]]; // _selectedAssets = [NSMutableArray arrayWithArray:@[asset]]; // open this code to send video / 打开这段代码发送视频 [[TZImageManager manager] getVideoOutputPathWithAsset:asset completion:^(NSString *outputPath) { NSLog(@"视频导出到本地完成,沙盒路径为:%@",outputPath); // Export completed, send video here, send by outputPath or NSData // 导出完成,在这里写上传代码,通过路径或者通过NSData上传 [MBProgressHUD hideHUDForView:self.controller.view]; }]; } // If user picking a gif image, this callback will be called. // 如果用户选择了一个gif图片,下面的handle会被执行 - (void)imagePickerController:(TZImagePickerController *)picker didFinishPickingGifImage:(UIImage *)animatedImage sourceAssets:(id)asset { [_selectedAssets addObject:asset]; [_selectedPhotos addObject:animatedImage]; [self startUploadAlbum]; } - (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event { [self.view endEditing:YES]; } #pragma mark - Private 印图片名字 /// 打印图片名字 - (void)printAssetsName:(NSArray *)assets { NSString *fileName; for (id asset in assets) { if ([asset isKindOfClass:[PHAsset class]]) { PHAsset *phAsset = (PHAsset *)asset; fileName = [phAsset valueForKey:@"filename"]; } else if ([asset isKindOfClass:[ALAsset class]]) { ALAsset *alAsset = (ALAsset *)asset; fileName = alAsset.defaultRepresentation.filename; } NSLog(@"图片名字:%@",fileName); } } - (UIInterfaceOrientationMask)supportedInterfaceOrientations { return UIInterfaceOrientationMaskPortrait; } #pragma mark - UIActionSheetDelegate - (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex { if (buttonIndex == 0) { // take photo / 去拍照 [self takePhoto]; } else if (buttonIndex == 1) { [self pushImagePickerController]; } } #pragma mark - UIAlertViewDelegate - (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex { if (buttonIndex == 1) { // 去设置界面,开启相机访问权限 if (iOS8Later) { [[UIApplication sharedApplication] openURL:[NSURL URLWithString:UIApplicationOpenSettingsURLString]]; } else { NSURL *privacyUrl; if (alertView.tag == 1) { // privacyUrl = [NSURL URLWithString:@"prefs:root=Privacy&path=PHOTOS"]; } else { // privacyUrl = [NSURL URLWithString:@"prefs:root=Privacy&path=CAMERA"]; } if ([[UIApplication sharedApplication] canOpenURL:privacyUrl]) { [[UIApplication sharedApplication] openURL:privacyUrl]; } else { UIAlertView * alert = [[UIAlertView alloc]initWithTitle:@"抱歉" message:@"无法跳转到隐私设置页面,请手动前往设置页面,谢谢" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles: nil]; [alert show]; } } } } #pragma mark - 改变相册选择页的导航栏外观 - (UIImagePickerController *)imagePickerVc { if (_imagePickerVc == nil) { _imagePickerVc = [[UIImagePickerController alloc] init]; _imagePickerVc.delegate = self; // set appearance / 改变相册选择页的导航栏外观 _imagePickerVc.navigationBar.barTintColor = self.navigationController.navigationBar.barTintColor; _imagePickerVc.navigationBar.tintColor = self.navigationController.navigationBar.tintColor; UIBarButtonItem *tzBarItem, *BarItem; if (iOS9Later) { tzBarItem = [UIBarButtonItem appearanceWhenContainedInInstancesOfClasses:@[[TZImagePickerController class]]]; BarItem = [UIBarButtonItem appearanceWhenContainedInInstancesOfClasses:@[[UIImagePickerController class]]]; } else { tzBarItem = [UIBarButtonItem appearanceWhenContainedIn:[TZImagePickerController class], nil]; BarItem = [UIBarButtonItem appearanceWhenContainedIn:[UIImagePickerController class], nil]; } NSDictionary *titleTextAttributes = [tzBarItem titleTextAttributesForState:UIControlStateNormal]; [BarItem setTitleTextAttributes:titleTextAttributes forState:UIControlStateNormal]; } return _imagePickerVc; } - (void)didReceiveMemoryWarning { [super didReceiveMemoryWarning]; // Dispose of any resources that can be recreated. } @end