KSMediaManager.m 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427
  1. //
  2. // KSMediaManager.m
  3. // MusicGradeExam
  4. //
  5. // Created by Kyle on 2020/7/10.
  6. // Copyright © 2020 DayaMusic. All rights reserved.
  7. //
  8. #import "KSMediaManager.h"
  9. #import "TZImageManager.h"
  10. #import <AssetsLibrary/AssetsLibrary.h>
  11. #import <Photos/Photos.h>
  12. #import "TZVideoPlayerController.h"
  13. #import "TZImagePickerController.h"
  14. #import "UIImage+ResizeImage.h"
  15. #import <UIDevice+YYAdd.h>
  16. #import <MobileCoreServices/MobileCoreServices.h>
  17. #define COLUMNNUMBER (3)
  18. @interface KSMediaManager ()<UIImagePickerControllerDelegate,UINavigationControllerDelegate,TZImagePickerControllerDelegate,UIAlertViewDelegate>
  19. {
  20. BOOL _isSelectOriginalPhoto;
  21. }
  22. @property (nonatomic, strong) UIImagePickerController *imagePickerVc;
  23. @property (nonatomic, copy) MediaCallback callback;
  24. @end
  25. @implementation KSMediaManager
  26. - (instancetype)init {
  27. if (self = [super init]) {
  28. [self configDefaultConfig];
  29. }
  30. return self;
  31. }
  32. - (void)configDefaultConfig {
  33. self.mediaType = MEDIATYPE_PHOTO;
  34. self.maxDuration = 480;
  35. self.maxPhotoNumber = 9;
  36. }
  37. - (void)showAlertCallbackWithBlock:(MediaCallback)callback {
  38. UIAlertController *alertVC = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:IS_IPAD ? UIAlertControllerStyleAlert : UIAlertControllerStyleActionSheet];
  39. [alertVC addAction:[UIAlertAction actionWithTitle:@"相机拍摄" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
  40. // 调用相机
  41. [self takePhoto];
  42. }]];
  43. [alertVC addAction:[UIAlertAction actionWithTitle:@"从手机相册选择" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
  44. // 调用相册
  45. [self pushImagePickerController];
  46. }]];
  47. [alertVC addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
  48. }]];
  49. alertVC.modalPresentationStyle = UIModalPresentationFullScreen;
  50. [self.baseCtrl presentViewController:alertVC animated:true completion:nil];
  51. if (callback) {
  52. self.callback = callback;
  53. }
  54. }
  55. - (void)noAlertCallback:(MediaCallback)callback {
  56. if (callback) {
  57. self.callback = callback;
  58. }
  59. }
  60. #pragma mark - TZImagePickerController
  61. - (void)extracted:(TZImagePickerController *)imagePickerVc {
  62. [imagePickerVc setDidFinishPickingPhotosHandle:^(NSArray<UIImage *> *photos, NSArray *assets, BOOL isSelectOriginalPhoto) {
  63. // 赋值
  64. if (self.callback) {
  65. dispatch_main_sync_safe(^{
  66. self.imageArray = [NSMutableArray arrayWithArray:photos];
  67. self.imageAsset = [NSMutableArray arrayWithArray:assets];
  68. self.callback(nil, self.imageArray, self.imageAsset);
  69. })
  70. }
  71. }];
  72. }
  73. - (void)pushImagePickerController {
  74. TZImagePickerController *imagePickerVc = [[TZImagePickerController alloc] initWithMaxImagesCount:self.maxPhotoNumber columnNumber:COLUMNNUMBER delegate:self];
  75. #pragma mark - 四类个性化设置,这些参数都可以不传,此时会走默认设置
  76. // 1.设置目前已经选中的图片数组
  77. imagePickerVc.selectedAssets = self.imageAsset; // 目前已经选中的图片数组
  78. imagePickerVc.isSelectOriginalPhoto = NO;
  79. // 2. Set the appearance
  80. // 2. 在这里设置imagePickerVc的外观
  81. [imagePickerVc.navigationBar setBarTintColor:THEMECOLOR];
  82. // 3. 设置是否可以选择视频/图片/原图
  83. if (self.mediaType == MEDIATYPE_ALL) {
  84. imagePickerVc.allowTakePicture = YES;
  85. imagePickerVc.allowTakeVideo = YES;
  86. imagePickerVc.allowPickingVideo = YES;
  87. imagePickerVc.allowPickingImage = YES;
  88. }
  89. else if (self.mediaType == MEDIATYPE_PHOTO) {
  90. imagePickerVc.allowTakePicture = YES;
  91. imagePickerVc.allowTakeVideo = NO;
  92. imagePickerVc.allowPickingVideo = NO;
  93. imagePickerVc.allowPickingImage = YES;
  94. }
  95. else if (self.mediaType == MEDIATYPE_VIDEO) {
  96. imagePickerVc.allowTakePicture = NO;
  97. imagePickerVc.allowTakeVideo = YES;
  98. imagePickerVc.allowPickingVideo = YES;
  99. imagePickerVc.allowPickingImage = NO;
  100. }
  101. imagePickerVc.videoMaximumDuration = self.maxDuration;
  102. // 设置视频拍摄质量
  103. [imagePickerVc setUiImagePickerControllerSettingBlock:^(UIImagePickerController *imagePickerController) {
  104. imagePickerController.videoQuality = UIImagePickerControllerQualityType640x480;
  105. }];
  106. imagePickerVc.allowCrop = self.maxPhotoNumber == 1 ? YES : NO; // 单张才需要裁剪
  107. imagePickerVc.needCircleCrop = NO;
  108. imagePickerVc.showSelectBtn = YES;
  109. NSInteger left = 30;
  110. NSInteger widthHeight = kScreenWidth - 2 * left;
  111. NSInteger top = (kScreenHeight - widthHeight) / 2;
  112. imagePickerVc.cropRect = CGRectMake(left, top, widthHeight, widthHeight);
  113. // 4. 照片排列按修改时间升序
  114. imagePickerVc.sortAscendingByModificationDate = NO;
  115. // You can get the photos by block, the same as by delegate.
  116. // 你可以通过block或者代理,来得到用户选择的照片.
  117. [self extracted:imagePickerVc];
  118. [imagePickerVc setDidFinishPickingVideoHandle:^(UIImage *coverImage, PHAsset *asset) {
  119. if (asset.duration >= self.maxDuration +1) {
  120. NSInteger minites = self.maxDuration / 60;
  121. NSString *tipsString = [NSString stringWithFormat:@"视频长度不能超过%zd分钟",minites];
  122. dispatch_main_async_safe(^{
  123. [MBProgressHUD ksShowMessage:tipsString];
  124. });
  125. return;
  126. }
  127. // PHAssetResource *resource = [[PHAssetResource assetResourcesForAsset:asset] firstObject];
  128. // long long size = [[resource valueForKey:@"fileSize"] longLongValue];
  129. //
  130. // NSLog(@"原视频大小:%@",[NSString stringWithFormat:@"%.2fM",(CGFloat)size/(1024*1024)]);
  131. dispatch_main_sync_safe(^{
  132. [MBProgressHUD ksShowHUDWithText:@"视频导出中..."];
  133. });
  134. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.3 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
  135. [[TZImageManager manager] getVideoOutputPathWithAsset:asset presetName:AVAssetExportPresetMediumQuality success:^(NSString *outputPath) {
  136. dispatch_main_sync_safe(^{
  137. [MBProgressHUD ksHideHUD];
  138. });
  139. NSLog(@"视频导出到本地完成,沙盒路径为:%@",outputPath);
  140. NSData *outputData = [NSData dataWithContentsOfURL:[NSURL fileURLWithPath:outputPath]]; //压缩后的视频
  141. NSLog(@"导出后的视频:%@",[NSString stringWithFormat:@"%.2fM",(CGFloat)outputData.length/(1024*1024)]);
  142. // Export completed, send video here, send by outputPath or NSData
  143. // 导出完成,在这里写上传代码,通过路径或者通过NSData上传
  144. if (self.callback) {
  145. dispatch_main_sync_safe(^{
  146. self.callback(outputPath, self.imageArray, self.imageAsset);
  147. });
  148. }
  149. } failure:^(NSString *errorMessage, NSError *error) {
  150. dispatch_main_sync_safe(^{
  151. [MBProgressHUD ksHideHUD];
  152. [MBProgressHUD ksShowMessage:@"视频导出失败"];
  153. });
  154. NSLog(@"视频导出失败:%@,error:%@",errorMessage, error);
  155. }];
  156. });
  157. }];
  158. imagePickerVc.modalPresentationStyle = UIModalPresentationFullScreen;
  159. [self.baseCtrl presentViewController:imagePickerVc animated:YES completion:nil];
  160. }
  161. #pragma mark - UIImagePickerController
  162. - (void)takePhoto {
  163. AVAuthorizationStatus authStatus = [AVCaptureDevice authorizationStatusForMediaType:AVMediaTypeVideo];
  164. if ((authStatus == AVAuthorizationStatusRestricted || authStatus == AVAuthorizationStatusDenied) && kiOS7Later) {
  165. // 无权限 做一个友好的提示
  166. #pragma clang diagnostic push
  167. #pragma clang diagnostic ignored "-Wdeprecated-declarations"
  168. UIAlertView * alert = [[UIAlertView alloc]initWithTitle:@"无法使用相机" message:@"请在iPhone的""设置-隐私-相机""中允许访问相机" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"设置", nil];
  169. [alert show];
  170. #define push clang diagnostic pop
  171. }
  172. else if (authStatus == AVAuthorizationStatusNotDetermined) {
  173. // 防止用户首次拍照拒绝授权时相机页黑屏
  174. [AVCaptureDevice requestAccessForMediaType:AVMediaTypeVideo completionHandler:^(BOOL granted) {
  175. if (granted) {
  176. dispatch_async(dispatch_get_main_queue(), ^{
  177. [self takePhoto];
  178. });
  179. }
  180. }];
  181. }
  182. else if ([PHPhotoLibrary authorizationStatus] == 2) { // 已被拒绝,没有相册权限,将无法保存拍的照片
  183. UIAlertView * alert = [[UIAlertView alloc]initWithTitle:@"无法访问相册" message:@"请在iPhone的""设置-隐私-相册""中允许访问相册" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"设置", nil];
  184. [alert show];
  185. }
  186. else if ([PHPhotoLibrary authorizationStatus] == 0) { // 未请求过相册权限
  187. [[TZImageManager manager] requestAuthorizationWithCompletion:^{
  188. [self takePhoto];
  189. }];
  190. }
  191. else { // 调用相机
  192. UIImagePickerControllerSourceType sourceType = UIImagePickerControllerSourceTypeCamera;
  193. if ([UIImagePickerController isSourceTypeAvailable: UIImagePickerControllerSourceTypeCamera]) {
  194. self.imagePickerVc.sourceType = sourceType;
  195. NSMutableArray *mediaTypes = [NSMutableArray array];
  196. if (self.mediaType == MEDIATYPE_ALL) {
  197. [mediaTypes addObject:(NSString *)kUTTypeMovie];
  198. [mediaTypes addObject:(NSString *)kUTTypeImage];
  199. }
  200. else if (self.mediaType == MEDIATYPE_VIDEO) {
  201. [mediaTypes addObject:(NSString *)kUTTypeMovie];
  202. }
  203. else {
  204. [mediaTypes addObject:(NSString *)kUTTypeImage];
  205. }
  206. self.imagePickerVc.mediaTypes = mediaTypes;
  207. self.imagePickerVc.videoMaximumDuration = self.maxDuration;
  208. if(kiOS8Later) {
  209. _imagePickerVc.modalPresentationStyle = UIModalPresentationOverCurrentContext;
  210. }
  211. _imagePickerVc.modalPresentationStyle = UIModalPresentationFullScreen;
  212. [self.baseCtrl presentViewController:_imagePickerVc animated:YES completion:nil];
  213. } else {
  214. NSLog(@"模拟器中无法打开照相机,请在真机中使用");
  215. }
  216. }
  217. }
  218. // 外部拍照进入的方法
  219. - (void)imagePickerController:(UIImagePickerController*)picker didFinishPickingMediaWithInfo:(NSDictionary *)info {
  220. [picker dismissViewControllerAnimated:YES completion:nil];
  221. NSString *type = [info objectForKey:UIImagePickerControllerMediaType];
  222. TZImagePickerController *tzImagePickerVc = [[TZImagePickerController alloc] initWithMaxImagesCount:self.maxPhotoNumber delegate:self];
  223. [tzImagePickerVc showProgressHUD];
  224. if ([type isEqualToString:@"public.image"]) {
  225. tzImagePickerVc.allowCrop = self.maxPhotoNumber == 1 ? YES : NO;
  226. tzImagePickerVc.needCircleCrop = NO;
  227. tzImagePickerVc.showSelectBtn = YES;
  228. tzImagePickerVc.sortAscendingByModificationDate = NO;
  229. UIImage *image = [info objectForKey:UIImagePickerControllerOriginalImage];
  230. // save photo and get asset / 保存图片,获取到asset
  231. [[TZImageManager manager] savePhotoWithImage:image completion:^(PHAsset *asset,NSError *error){
  232. [tzImagePickerVc hideProgressHUD];
  233. if (error) { // 如果保存失败,基本是没有相册权限导致的...
  234. [tzImagePickerVc hideProgressHUD];
  235. NSLog(@"图片保存失败 %@",error);
  236. UIAlertView * alert = [[UIAlertView alloc]initWithTitle:@"无法保存图片" message:@"请在iPhone的""设置-隐私-相册""中允许访问相册" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"设置", nil];
  237. alert.tag = 1;
  238. [alert show];
  239. } else {
  240. TZAssetModel *assetModel = [[TZImageManager manager] createModelWithAsset:asset];
  241. if (self.maxPhotoNumber == 1) {
  242. TZImagePickerController *imagePicker = [[TZImagePickerController alloc] initCropTypeWithAsset:assetModel.asset photo:image completion:^(UIImage *cropImage, id asset) {
  243. // 回调
  244. if (self.callback) {
  245. self.imageArray = [NSMutableArray arrayWithObject:cropImage];
  246. self.imageAsset = [NSMutableArray arrayWithObject:asset];
  247. dispatch_async(dispatch_get_main_queue(), ^{
  248. self.callback(nil, self.imageArray, self.imageAsset);
  249. });
  250. }
  251. }];
  252. imagePicker.allowPickingImage = YES;
  253. imagePicker.allowCrop = YES;
  254. imagePicker.needCircleCrop = NO;
  255. NSInteger left = 30;
  256. NSInteger widthHeight = kScreenWidth - 2 * left;
  257. NSInteger top = (kScreenHeight - widthHeight) / 2;
  258. imagePicker.cropRect = CGRectMake(left, top, widthHeight, widthHeight);
  259. imagePicker.modalPresentationStyle = UIModalPresentationFullScreen;
  260. [self.baseCtrl presentViewController:imagePicker animated:YES completion:nil];
  261. }
  262. else {
  263. if (self.callback) {
  264. self.imageArray = [NSMutableArray arrayWithObject:image];
  265. self.imageAsset = [NSMutableArray arrayWithObject:assetModel.asset];
  266. dispatch_async(dispatch_get_main_queue(), ^{
  267. self.callback(nil, self.imageArray, self.imageAsset);
  268. });
  269. }
  270. }
  271. }
  272. }];
  273. }
  274. else if ([type isEqualToString:@"public.movie"]) {
  275. tzImagePickerVc.videoMaximumDuration = self.maxDuration;
  276. // 设置视频拍摄质量
  277. [tzImagePickerVc setUiImagePickerControllerSettingBlock:^(UIImagePickerController *imagePickerController) {
  278. imagePickerController.videoQuality = UIImagePickerControllerQualityType640x480;
  279. }];
  280. NSURL *videoUrl = [info objectForKey:UIImagePickerControllerMediaURL];
  281. if (videoUrl) {
  282. [[TZImageManager manager] saveVideoWithUrl:videoUrl completion:^(PHAsset *asset, NSError *error) {
  283. [tzImagePickerVc hideProgressHUD];
  284. if (!error) {
  285. dispatch_main_async_safe(^{
  286. [MBProgressHUD ksShowHUDWithText:@"视频处理中..."];
  287. });
  288. [[TZImageManager manager] getVideoOutputPathWithAsset:asset presetName:AVAssetExportPresetMediumQuality success:^(NSString *outputPath) {
  289. // NSData *data = [NSData dataWithContentsOfFile:outputPath];
  290. dispatch_main_async_safe(^{
  291. [MBProgressHUD ksHideHUD];
  292. });
  293. NSLog(@"视频导出到本地完成,沙盒路径为:%@",outputPath);
  294. // Export completed, send video here, send by outputPath or NSData
  295. // 导出完成,在这里写上传代码,通过路径或者通过NSData上传
  296. NSData *outputData = [NSData dataWithContentsOfURL:[NSURL fileURLWithPath:outputPath]]; //压缩后的视频
  297. NSLog(@"导出后的视频:%@",[NSString stringWithFormat:@"%.2fM",(CGFloat)outputData.length/(1024*1024)]);
  298. // Export completed, send video here, send by outputPath or NSData
  299. // 导出完成,在这里写上传代码,通过路径或者通过NSData上传
  300. if (self.callback) {
  301. self.callback(outputPath, self.imageArray, self.imageAsset);
  302. }
  303. } failure:^(NSString *errorMessage, NSError *error) {
  304. dispatch_main_async_safe(^{
  305. [MBProgressHUD ksHideHUD];
  306. [MBProgressHUD ksShowMessage:@"视频导出失败"];
  307. });
  308. NSLog(@"视频导出失败:%@,error:%@",errorMessage, error);
  309. }];
  310. }
  311. }];
  312. }
  313. }
  314. }
  315. - (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker {
  316. if ([picker isKindOfClass:[UIImagePickerController class]]) {
  317. [picker dismissViewControllerAnimated:YES completion:nil];
  318. }
  319. }
  320. #pragma mark - getter
  321. - (NSMutableArray *)imageArray {
  322. if (!_imageArray) {
  323. _imageArray = [NSMutableArray array];
  324. }
  325. return _imageArray;
  326. }
  327. - (NSMutableArray *)imageAsset {
  328. if (!_imageAsset) {
  329. _imageAsset = [NSMutableArray array];
  330. }
  331. return _imageAsset;
  332. }
  333. - (UIImagePickerController *)imagePickerVc {
  334. if (_imagePickerVc == nil) {
  335. _imagePickerVc = [[UIImagePickerController alloc] init];
  336. _imagePickerVc.delegate = self;
  337. // set appearance / 改变相册选择页的导航栏外观
  338. _imagePickerVc.navigationBar.barTintColor = self.baseCtrl.navigationController.navigationBar.barTintColor;
  339. _imagePickerVc.navigationBar.tintColor = self.baseCtrl.navigationController.navigationBar.tintColor;
  340. UIBarButtonItem *tzBarItem, *BarItem;
  341. if (kiOS9Later) {
  342. tzBarItem = [UIBarButtonItem appearanceWhenContainedInInstancesOfClasses:@[[TZImagePickerController class]]];
  343. BarItem = [UIBarButtonItem appearanceWhenContainedInInstancesOfClasses:@[[UIImagePickerController class]]];
  344. } else {
  345. #pragma clang diagnostic push
  346. #pragma clang diagnostic ignored "-Wdeprecated-declarations"
  347. tzBarItem = [UIBarButtonItem appearanceWhenContainedIn:[TZImagePickerController class], nil];
  348. BarItem = [UIBarButtonItem appearanceWhenContainedIn:[UIImagePickerController class], nil];
  349. #pragma clang diagnostic pop
  350. }
  351. NSDictionary *titleTextAttributes = [tzBarItem titleTextAttributesForState:UIControlStateNormal];
  352. [BarItem setTitleTextAttributes:titleTextAttributes forState:UIControlStateNormal];
  353. }
  354. return _imagePickerVc;
  355. }
  356. #pragma mark - UIAlertViewDelegate
  357. #pragma clang diagnostic push
  358. #pragma clang diagnostic ignored "-Wdeprecated-declarations"
  359. - (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex {
  360. if (buttonIndex == 1) { // 去设置界面,开启相机访问权限
  361. [[UIApplication sharedApplication] openURL:[NSURL URLWithString:UIApplicationOpenSettingsURLString]];
  362. }
  363. }
  364. #define push clang diagnostic pop
  365. #pragma mark ---- setting
  366. - (void)setMaxDuration:(NSInteger)maxDuration {
  367. _maxDuration = maxDuration;
  368. }
  369. - (void)setMediaType:(MEDIATYPE)mediaType {
  370. _mediaType = mediaType;
  371. if (mediaType == MEDIATYPE_PHOTO) {
  372. self.maxPhotoNumber = 9;
  373. }
  374. else if (mediaType == MEDIATYPE_VIDEO) {
  375. self.maxPhotoNumber = 1;
  376. }
  377. else if (mediaType == MEDIATYPE_ALL) {
  378. self.maxPhotoNumber = 2;
  379. }
  380. }
  381. @end