NewChoiceFileController.m 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483
  1. //
  2. // NewChoiceFileController.m
  3. // SiBenClient
  4. //
  5. // Created by 肖雨 on 2017/9/22.
  6. // Copyright © 2017年 ShangLv. All rights reserved.
  7. //
  8. #import "NewChoiceFileController.h"
  9. #import "TZImagePickerController.h"
  10. #import "UIView+Layout.h"
  11. #import "TZTestCell.h"
  12. #import <AssetsLibrary/AssetsLibrary.h>
  13. #import <Photos/Photos.h>
  14. #import "LxGridViewFlowLayout.h"
  15. #import "TZImageManager.h"
  16. #import "TZVideoPlayerController.h"
  17. #import "TZPhotoPreviewController.h"
  18. #import "TZGifPhotoPreviewController.h"
  19. @interface NewChoiceFileController()<TZImagePickerControllerDelegate,UIActionSheetDelegate,UIImagePickerControllerDelegate,UIAlertViewDelegate,UINavigationControllerDelegate>
  20. {
  21. NSMutableArray *_selectedPhotos;
  22. NSMutableArray *_selectedAssets;
  23. }
  24. @property (nonatomic,copy) void(^screenAction)(NSString *imagePath);
  25. @property (nonatomic, strong) UIImagePickerController *imagePickerVc;
  26. @property (nonatomic, weak) UIViewController *controller;
  27. @property (nonatomic, copy) NSString *Type;
  28. @property (nonatomic, assign) BOOL isSelectOriginalPhoto;
  29. @end
  30. @implementation NewChoiceFileController
  31. - (void)dealloc
  32. {
  33. //此类根据上级类销毁而销毁 上级界面需要主动销毁此类,复制此段代码
  34. /*
  35. - (void)dealloc
  36. {
  37. 第一步,用willMoveToParentViewController这个方法,并把参数设置为nil,通知VC这个Controller即将被移除父视图控制器。
  38. 第二步,把VC.view移除出父视图控制器的view。
  39. 第三步,然后用removeFromParentViewcontroller这个方法把VC彻底移除。
  40. if (cont) {
  41. [cont willMoveToParentViewController:nil];
  42. [cont.view removeFromSuperview];
  43. [cont removeFromParentViewController];
  44. }
  45. }
  46. */
  47. NSLog(@"选择文件界面销毁");
  48. }
  49. #pragma mark - 上传照片
  50. - (void)startUploadAlbum
  51. {
  52. if (_selectedPhotos.count <= 0) {
  53. [self.controller.view makeToast:@"请添加上传图片" duration:1.0 position:CSToastPositionCenter];
  54. return;
  55. }else {
  56. [MBProgressHUD showLoadToView:self.controller.view title:@"正在上传,请稍后..."];
  57. }
  58. NSMutableArray *imageUploadArray = [NSMutableArray array];
  59. NSString *imagtype;
  60. for (int i=0; i<_selectedPhotos.count; i++) {
  61. //获取图片名称
  62. NSString *fileName;
  63. id asset = _selectedAssets[i];
  64. if ([asset isKindOfClass:[PHAsset class]]) {
  65. PHAsset *phAsset = (PHAsset *)asset;
  66. fileName = [phAsset valueForKey:@"filename"];
  67. } else if ([asset isKindOfClass:[ALAsset class]]) {
  68. ALAsset *alAsset = (ALAsset *)asset;
  69. fileName = alAsset.defaultRepresentation.filename;
  70. }
  71. NSArray *array = [fileName componentsSeparatedByString:@"."];
  72. // if (![[array lastObject] isEqualToString:@"JPG"] && ![[array lastObject] isEqualToString:@"JPEG"] && ![[array lastObject] isEqualToString:@"PNG"]) {
  73. //
  74. // [MBProgressHUD hideHUDForView:self.view];
  75. // [MBProgressHUD showError:@"暂不支持该图片格式上传" toView:self.view];
  76. // return;
  77. // }
  78. NSLog(@"正在上传的图片格式为: %@",[array lastObject]);
  79. imagtype = [array lastObject];
  80. UIImage *ysImage = _selectedPhotos[i];
  81. NSData *ysImageDataSize = UIImageJPEGRepresentation(ysImage, 1.0);
  82. //如果图片大小没有超过500KB 则不进行压缩
  83. if ([ysImageDataSize length]/1000 > 500) {
  84. CGSize ysImageSize = ysImage.size;
  85. ysImageSize.width *= 0.45;
  86. ysImageSize.height *= 0.45;
  87. ysImage = [self imageWithImage:ysImage scaledToSize:ysImageSize];
  88. NSData *ysImageData = [NSData dataWithData:UIImageJPEGRepresentation(ysImage,0.7)];
  89. //image=[UIImage imageWithData:imageData];
  90. [imageUploadArray addObject:ysImageData];
  91. NSLog(@"压缩图片大小 = %lu\n 原图大小 = %lu ",[ysImageData length]/1000,[ysImageDataSize length]/1000);
  92. }else {
  93. [imageUploadArray addObject:ysImageDataSize];
  94. }
  95. }
  96. NSMutableDictionary *parameters = NewMutableDictionaryInit;
  97. NSString *url;
  98. NSString *sign;
  99. if ([self.Type isEqualToString:@"发布成果"]) {
  100. url = JT_uploadPicture;
  101. sign = @"achievement_picture";
  102. }else if([self.Type isEqualToString:@"发布需求"]){
  103. url = JT_uploadPicture;
  104. sign = @"demand_picture";
  105. }else{
  106. url = JT_uploadImg;
  107. }
  108. [parameters safeSetObject:sign forKey:@"sign"];//成果
  109. [NetworkRequestManager requestPostWithInterfacePrefix:url serverFileName:@"file" parameters:parameters arrayParameters:imageUploadArray imagetype:imagtype onSuccess:^(id requestData) {
  110. [MBProgressHUD hideHUDForView:self.controller.view];
  111. NSLog(@"服务器返回的报文: %@",requestData);
  112. if ([self.Type isEqualToString:@"发布成果"]) {
  113. [MBProgressHUD showSuccess:@"上传成功" toView:self.view];
  114. }else if([self.Type isEqualToString:@"发布成果"]){
  115. [MBProgressHUD showSuccess:@"上传成功" toView:self.view];
  116. }else{
  117. [MBProgressHUD showSuccess:@"修改头像成功" toView:self.view];
  118. }
  119. _screenAction(requestData[@"data"]);
  120. } onFailure:^{
  121. [MBProgressHUD hideHUDForView:self.controller.view];
  122. }];
  123. }
  124. //后置摄像头情况下
  125. //这时图片的体积在100k左右(iphone5s下,6多了几十k,plus没有真机),1000*几百的分辨率且清晰
  126. -(UIImage*)imageWithImage:(UIImage*)image scaledToSize:(CGSize)newSize
  127. {
  128. UIGraphicsBeginImageContextWithOptions(newSize, NO, 0.0);
  129. [image drawInRect:CGRectMake(0, 0, newSize.width, newSize.height)];
  130. UIImage* scaledImage = UIGraphicsGetImageFromCurrentImageContext();
  131. UIGraphicsEndImageContext();
  132. return scaledImage;
  133. }
  134. - (void)viewDidLoad
  135. {
  136. [super viewDidLoad];
  137. // Do any additional setup after loading the view.
  138. _selectedPhotos = NewMutableArrayInit;
  139. _selectedAssets = NewMutableArrayInit;
  140. }
  141. #pragma mark - 拍照/相册
  142. - (void)choiceFile:(UIViewController *)controller type:(NSString *)type action:(void(^)(NSString *imagePath))action
  143. {
  144. self.screenAction = action;
  145. self.controller = controller;
  146. self.Type = type;
  147. [_selectedAssets removeAllObjects];
  148. [_selectedPhotos removeAllObjects];
  149. UIActionSheet *sheet = [[UIActionSheet alloc] initWithTitle:nil delegate:self cancelButtonTitle:@"取消" destructiveButtonTitle:nil otherButtonTitles:@"拍照",@"去相册选择", nil];
  150. [sheet showInView:self.view];
  151. }
  152. #pragma mark - UIImagePickerController
  153. - (void)takePhoto {
  154. AVAuthorizationStatus authStatus = [AVCaptureDevice authorizationStatusForMediaType:AVMediaTypeVideo];
  155. if ((authStatus == AVAuthorizationStatusRestricted || authStatus == AVAuthorizationStatusDenied)) {// && iOS7Later
  156. // 无相机权限 做一个友好的提示
  157. UIAlertView * alert = [[UIAlertView alloc]initWithTitle:@"无法使用相机" message:@"请在iPhone的""设置-隐私-相机""中允许访问相机" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"设置", nil];
  158. [alert show];
  159. // 拍照之前还需要检查相册权限
  160. }
  161. /*
  162. else if ([TZImageManager authorizationStatus] == 2) { // 已被拒绝,没有相册权限,将无法保存拍的照片
  163. UIAlertView * alert = [[UIAlertView alloc]initWithTitle:@"无法访问相册" message:@"请在iPhone的""设置-隐私-相册""中允许访问相册" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"设置", nil];
  164. alert.tag = 1;
  165. [alert show];
  166. }
  167. */
  168. else { // 调用相机
  169. UIImagePickerControllerSourceType sourceType = UIImagePickerControllerSourceTypeCamera;
  170. if ([UIImagePickerController isSourceTypeAvailable: UIImagePickerControllerSourceTypeCamera]) {
  171. self.imagePickerVc.sourceType = sourceType;
  172. if(iOS8Later) {
  173. _imagePickerVc.modalPresentationStyle = UIModalPresentationOverCurrentContext;
  174. }
  175. [self presentViewController:_imagePickerVc animated:YES completion:nil];
  176. } else {
  177. NSLog(@"模拟器中无法打开照相机,请在真机中使用");
  178. }
  179. }
  180. }
  181. - (void)imagePickerController:(UIImagePickerController*)picker didFinishPickingMediaWithInfo:(NSDictionary *)info {
  182. [picker dismissViewControllerAnimated:YES completion:nil];
  183. NSString *type = [info objectForKey:UIImagePickerControllerMediaType];
  184. if ([type isEqualToString:@"public.image"]) {
  185. TZImagePickerController *tzImagePickerVc = [[TZImagePickerController alloc] initWithMaxImagesCount:1 delegate:self];
  186. tzImagePickerVc.sortAscendingByModificationDate = YES;
  187. [tzImagePickerVc showProgressHUD];
  188. UIImage *image = [info objectForKey:UIImagePickerControllerOriginalImage];
  189. // save photo and get asset / 保存图片,获取到asset
  190. [[TZImageManager manager] savePhotoWithImage:image completion:^(NSError *error){
  191. if (error) {
  192. [tzImagePickerVc hideProgressHUD];
  193. NSLog(@"图片保存失败 %@",error);
  194. } else {
  195. [[TZImageManager manager] getCameraRollAlbum:NO allowPickingImage:YES completion:^(TZAlbumModel *model) {
  196. [[TZImageManager manager] getAssetsFromFetchResult:model.result allowPickingVideo:NO allowPickingImage:YES completion:^(NSArray<TZAssetModel *> *models) {
  197. [tzImagePickerVc hideProgressHUD];
  198. TZAssetModel *assetModel = [models firstObject];
  199. if (tzImagePickerVc.sortAscendingByModificationDate) {
  200. assetModel = [models lastObject];
  201. }
  202. [self refreshCollectionViewWithAddedAsset:assetModel.asset image:image];
  203. }];
  204. }];
  205. }
  206. }];
  207. }
  208. }
  209. //拍照之后获得的图片
  210. - (void)refreshCollectionViewWithAddedAsset:(id)asset image:(UIImage *)image {
  211. [_selectedAssets addObject:asset];
  212. [_selectedPhotos addObject:image];
  213. [self startUploadAlbum];
  214. }
  215. //取消拍照
  216. - (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker {
  217. if ([picker isKindOfClass:[UIImagePickerController class]]) {
  218. [picker dismissViewControllerAnimated:YES completion:nil];
  219. }
  220. }
  221. #pragma mark - TZImagePickerController
  222. - (void)pushImagePickerController {
  223. TZImagePickerController *imagePickerVc = [[TZImagePickerController alloc] initWithMaxImagesCount:1 columnNumber:1 delegate:self pushPhotoPickerVc:YES];
  224. #pragma mark - 四类个性化设置,这些参数都可以不传,此时会走默认设置
  225. imagePickerVc.isSelectOriginalPhoto = _isSelectOriginalPhoto;
  226. imagePickerVc.allowTakePicture = NO; // 在内部显示拍照按钮
  227. // 2. Set the appearance
  228. // 2. 在这里设置imagePickerVc的外观
  229. // imagePickerVc.navigationBar.barTintColor = [UIColor greenColor];
  230. // imagePickerVc.oKButtonTitleColorDisabled = [UIColor lightGrayColor];
  231. // imagePickerVc.oKButtonTitleColorNormal = [UIColor greenColor];
  232. // imagePickerVc.navigationBar.translucent = NO;
  233. // 3. Set allow picking video & photo & originalPhoto or not
  234. // 3. 设置是否可以选择视频/图片/原图
  235. imagePickerVc.allowPickingVideo = NO;
  236. imagePickerVc.allowPickingImage = YES;
  237. imagePickerVc.allowPickingOriginalPhoto = YES;
  238. imagePickerVc.allowPickingGif = NO;
  239. // 4. 照片排列按修改时间升序
  240. imagePickerVc.sortAscendingByModificationDate = YES;
  241. // imagePickerVc.minImagesCount = 3;
  242. // imagePickerVc.alwaysEnableDoneBtn = YES;
  243. // imagePickerVc.minPhotoWidthSelectable = 3000;
  244. // imagePickerVc.minPhotoHeightSelectable = 2000;
  245. /// 5. Single selection mode, valid when maxImagesCount = 1
  246. /// 5. 单选模式,maxImagesCount为1时才生效
  247. imagePickerVc.showSelectBtn = NO;
  248. imagePickerVc.allowCrop = NO;
  249. imagePickerVc.needCircleCrop = NO;
  250. imagePickerVc.circleCropRadius = 100;
  251. // [imagePickerVc setCropViewSettingBlock:^(UIView *cropView) {
  252. // cropView.layer.borderColor = [UIColor redColor].CGColor;
  253. // cropView.layer.borderWidth = 2.0;
  254. // }];
  255. //imagePickerVc.allowPreview = NO;
  256. #pragma mark - 到这里为止
  257. // You can get the photos by block, the same as by delegate.
  258. // 你可以通过block或者代理,来得到用户选择的照片.
  259. [imagePickerVc setDidFinishPickingPhotosHandle:^(NSArray<UIImage *> *photos, NSArray *assets, BOOL isSelectOriginalPhoto) {
  260. }];
  261. [self.controller presentViewController:imagePickerVc animated:YES completion:nil];
  262. }
  263. #pragma mark - TZImagePickerControllerDelegate
  264. /// User click cancel button
  265. /// 用户点击了取消
  266. - (void)tz_imagePickerControllerDidCancel:(TZImagePickerController *)picker {
  267. NSLog(@"取消选择相册");
  268. }
  269. // The picker should dismiss itself; when it dismissed these handle will be called.
  270. // If isOriginalPhoto is YES, user picked the original photo.
  271. // You can get original photo with asset, by the method [[TZImageManager manager] getOriginalPhotoWithAsset:completion:].
  272. // The UIImage Object in photos default width is 828px, you can set it by photoWidth property.
  273. // 这个照片选择器会自己dismiss,当选择器dismiss的时候,会执行下面的代理方法
  274. // 如果isSelectOriginalPhoto为YES,表明用户选择了原图
  275. // 你可以通过一个asset获得原图,通过这个方法:[[TZImageManager manager] getOriginalPhotoWithAsset:completion:]
  276. // photos数组里的UIImage对象,默认是828像素宽,你可以通过设置photoWidth属性的值来改变它
  277. - (void)imagePickerController:(TZImagePickerController *)picker didFinishPickingPhotos:(NSArray *)photos sourceAssets:(NSArray *)assets isSelectOriginalPhoto:(BOOL)isSelectOriginalPhoto {
  278. _isSelectOriginalPhoto = isSelectOriginalPhoto;
  279. // 1.打印图片名字
  280. [self printAssetsName:assets];
  281. [_selectedAssets addObjectsFromArray:assets];
  282. [_selectedPhotos addObjectsFromArray:photos];
  283. [self startUploadAlbum];
  284. }
  285. // If user picking a video, this callback will be called.
  286. // If system version > iOS8,asset is kind of PHAsset class, else is ALAsset class.
  287. // 如果用户选择了一个视频,下面的handle会被执行
  288. // 如果系统版本大于iOS8,asset是PHAsset类的对象,否则是ALAsset类的对象
  289. - (void)imagePickerController:(TZImagePickerController *)picker didFinishPickingVideo:(UIImage *)coverImage sourceAssets:(id)asset {
  290. [MBProgressHUD showLoadToView:self.controller.view title:@"请稍后,正在准备上传缓存..."];
  291. // _selectedPhotos = [NSMutableArray arrayWithArray:@[coverImage]];
  292. // _selectedAssets = [NSMutableArray arrayWithArray:@[asset]];
  293. // open this code to send video / 打开这段代码发送视频
  294. [[TZImageManager manager] getVideoOutputPathWithAsset:asset completion:^(NSString *outputPath) {
  295. NSLog(@"视频导出到本地完成,沙盒路径为:%@",outputPath);
  296. // Export completed, send video here, send by outputPath or NSData
  297. // 导出完成,在这里写上传代码,通过路径或者通过NSData上传
  298. [MBProgressHUD hideHUDForView:self.controller.view];
  299. }];
  300. }
  301. // If user picking a gif image, this callback will be called.
  302. // 如果用户选择了一个gif图片,下面的handle会被执行
  303. - (void)imagePickerController:(TZImagePickerController *)picker didFinishPickingGifImage:(UIImage *)animatedImage sourceAssets:(id)asset {
  304. [_selectedAssets addObject:asset];
  305. [_selectedPhotos addObject:animatedImage];
  306. [self startUploadAlbum];
  307. }
  308. - (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
  309. [self.view endEditing:YES];
  310. }
  311. #pragma mark - Private 印图片名字
  312. /// 打印图片名字
  313. - (void)printAssetsName:(NSArray *)assets {
  314. NSString *fileName;
  315. for (id asset in assets) {
  316. if ([asset isKindOfClass:[PHAsset class]]) {
  317. PHAsset *phAsset = (PHAsset *)asset;
  318. fileName = [phAsset valueForKey:@"filename"];
  319. } else if ([asset isKindOfClass:[ALAsset class]]) {
  320. ALAsset *alAsset = (ALAsset *)asset;
  321. fileName = alAsset.defaultRepresentation.filename;
  322. }
  323. NSLog(@"图片名字:%@",fileName);
  324. }
  325. }
  326. - (UIInterfaceOrientationMask)supportedInterfaceOrientations {
  327. return UIInterfaceOrientationMaskPortrait;
  328. }
  329. #pragma mark - UIActionSheetDelegate
  330. - (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex {
  331. if (buttonIndex == 0) { // take photo / 去拍照
  332. [self takePhoto];
  333. } else if (buttonIndex == 1) {
  334. [self pushImagePickerController];
  335. }
  336. }
  337. #pragma mark - UIAlertViewDelegate
  338. - (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex {
  339. if (buttonIndex == 1) { // 去设置界面,开启相机访问权限
  340. if (iOS8Later) {
  341. [[UIApplication sharedApplication] openURL:[NSURL URLWithString:UIApplicationOpenSettingsURLString]];
  342. } else {
  343. NSURL *privacyUrl;
  344. if (alertView.tag == 1) {
  345. // privacyUrl = [NSURL URLWithString:@"prefs:root=Privacy&path=PHOTOS"];
  346. } else {
  347. // privacyUrl = [NSURL URLWithString:@"prefs:root=Privacy&path=CAMERA"];
  348. }
  349. if ([[UIApplication sharedApplication] canOpenURL:privacyUrl]) {
  350. [[UIApplication sharedApplication] openURL:privacyUrl];
  351. } else {
  352. UIAlertView * alert = [[UIAlertView alloc]initWithTitle:@"抱歉" message:@"无法跳转到隐私设置页面,请手动前往设置页面,谢谢" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles: nil];
  353. [alert show];
  354. }
  355. }
  356. }
  357. }
  358. #pragma mark - 改变相册选择页的导航栏外观
  359. - (UIImagePickerController *)imagePickerVc {
  360. if (_imagePickerVc == nil) {
  361. _imagePickerVc = [[UIImagePickerController alloc] init];
  362. _imagePickerVc.delegate = self;
  363. // set appearance / 改变相册选择页的导航栏外观
  364. _imagePickerVc.navigationBar.barTintColor = self.navigationController.navigationBar.barTintColor;
  365. _imagePickerVc.navigationBar.tintColor = self.navigationController.navigationBar.tintColor;
  366. UIBarButtonItem *tzBarItem, *BarItem;
  367. if (iOS9Later) {
  368. tzBarItem = [UIBarButtonItem appearanceWhenContainedInInstancesOfClasses:@[[TZImagePickerController class]]];
  369. BarItem = [UIBarButtonItem appearanceWhenContainedInInstancesOfClasses:@[[UIImagePickerController class]]];
  370. } else {
  371. tzBarItem = [UIBarButtonItem appearanceWhenContainedIn:[TZImagePickerController class], nil];
  372. BarItem = [UIBarButtonItem appearanceWhenContainedIn:[UIImagePickerController class], nil];
  373. }
  374. NSDictionary *titleTextAttributes = [tzBarItem titleTextAttributesForState:UIControlStateNormal];
  375. [BarItem setTitleTextAttributes:titleTextAttributes forState:UIControlStateNormal];
  376. }
  377. return _imagePickerVc;
  378. }
  379. - (void)didReceiveMemoryWarning {
  380. [super didReceiveMemoryWarning];
  381. // Dispose of any resources that can be recreated.
  382. }
  383. @end