KSMediaManager.m 20 KB

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