TZPhotoPickerController.m 51 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056
  1. //
  2. // TZPhotoPickerController.m
  3. // TZImagePickerController
  4. //
  5. // Created by 谭真 on 15/12/24.
  6. // Copyright © 2015年 谭真. All rights reserved.
  7. //
  8. #import "TZPhotoPickerController.h"
  9. #import "TZImagePickerController.h"
  10. #import "TZPhotoPreviewController.h"
  11. #import "TZAssetCell.h"
  12. #import "TZAssetModel.h"
  13. #import "UIView+Layout.h"
  14. #import "TZImageManager.h"
  15. #import "TZVideoPlayerController.h"
  16. #import "TZGifPhotoPreviewController.h"
  17. #import "TZLocationManager.h"
  18. #import <MobileCoreServices/MobileCoreServices.h>
  19. #import "TZImageRequestOperation.h"
  20. @interface TZPhotoPickerController ()<UICollectionViewDataSource,UICollectionViewDelegate,UIImagePickerControllerDelegate,UINavigationControllerDelegate,UIAlertViewDelegate> {
  21. NSMutableArray *_models;
  22. UIView *_bottomToolBar;
  23. UIButton *_previewButton;
  24. UIButton *_doneButton;
  25. UIImageView *_numberImageView;
  26. UILabel *_numberLabel;
  27. UIButton *_originalPhotoButton;
  28. UILabel *_originalPhotoLabel;
  29. UIView *_divideLine;
  30. BOOL _shouldScrollToBottom;
  31. BOOL _showTakePhotoBtn;
  32. CGFloat _offsetItemCount;
  33. }
  34. @property CGRect previousPreheatRect;
  35. @property (nonatomic, assign) BOOL isSelectOriginalPhoto;
  36. @property (nonatomic, strong) TZCollectionView *collectionView;
  37. @property (nonatomic, strong) UILabel *noDataLabel;
  38. @property (strong, nonatomic) UICollectionViewFlowLayout *layout;
  39. @property (nonatomic, strong) UIImagePickerController *imagePickerVc;
  40. @property (strong, nonatomic) CLLocation *location;
  41. @property (nonatomic, strong) NSOperationQueue *operationQueue;
  42. @end
  43. static CGSize AssetGridThumbnailSize;
  44. static CGFloat itemMargin = 5;
  45. @implementation TZPhotoPickerController
  46. #pragma clang diagnostic push
  47. #pragma clang diagnostic ignored "-Wdeprecated-declarations"
  48. - (UIImagePickerController *)imagePickerVc {
  49. if (_imagePickerVc == nil) {
  50. _imagePickerVc = [[UIImagePickerController alloc] init];
  51. _imagePickerVc.delegate = self;
  52. // set appearance / 改变相册选择页的导航栏外观
  53. _imagePickerVc.navigationBar.barTintColor = self.navigationController.navigationBar.barTintColor;
  54. _imagePickerVc.navigationBar.tintColor = self.navigationController.navigationBar.tintColor;
  55. UIBarButtonItem *tzBarItem, *BarItem;
  56. if (@available(iOS 9, *)) {
  57. tzBarItem = [UIBarButtonItem appearanceWhenContainedInInstancesOfClasses:@[[TZImagePickerController class]]];
  58. BarItem = [UIBarButtonItem appearanceWhenContainedInInstancesOfClasses:@[[UIImagePickerController class]]];
  59. } else {
  60. tzBarItem = [UIBarButtonItem appearanceWhenContainedIn:[TZImagePickerController class], nil];
  61. BarItem = [UIBarButtonItem appearanceWhenContainedIn:[UIImagePickerController class], nil];
  62. }
  63. NSDictionary *titleTextAttributes = [tzBarItem titleTextAttributesForState:UIControlStateNormal];
  64. [BarItem setTitleTextAttributes:titleTextAttributes forState:UIControlStateNormal];
  65. }
  66. return _imagePickerVc;
  67. }
  68. - (void)viewDidLoad {
  69. [super viewDidLoad];
  70. self.isFirstAppear = YES;
  71. TZImagePickerController *tzImagePickerVc = (TZImagePickerController *)self.navigationController;
  72. _isSelectOriginalPhoto = tzImagePickerVc.isSelectOriginalPhoto;
  73. _shouldScrollToBottom = YES;
  74. self.view.backgroundColor = [UIColor whiteColor];
  75. self.navigationItem.title = _model.name;
  76. self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:tzImagePickerVc.cancelBtnTitleStr style:UIBarButtonItemStylePlain target:tzImagePickerVc action:@selector(cancelButtonClick)];
  77. if (tzImagePickerVc.navLeftBarButtonSettingBlock) {
  78. UIButton *leftButton = [UIButton buttonWithType:UIButtonTypeCustom];
  79. leftButton.frame = CGRectMake(0, 0, 44, 44);
  80. [leftButton addTarget:self action:@selector(navLeftBarButtonClick) forControlEvents:UIControlEventTouchUpInside];
  81. tzImagePickerVc.navLeftBarButtonSettingBlock(leftButton);
  82. self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:leftButton];
  83. } else if (tzImagePickerVc.childViewControllers.count) {
  84. [tzImagePickerVc.childViewControllers firstObject].navigationItem.backBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:[NSBundle tz_localizedStringForKey:@"Back"] style:UIBarButtonItemStylePlain target:nil action:nil];
  85. }
  86. _showTakePhotoBtn = _model.isCameraRoll && ((tzImagePickerVc.allowTakePicture && tzImagePickerVc.allowPickingImage) || (tzImagePickerVc.allowTakeVideo && tzImagePickerVc.allowPickingVideo));
  87. // [self resetCachedAssets];
  88. [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(didChangeStatusBarOrientationNotification:) name:UIApplicationDidChangeStatusBarOrientationNotification object:nil];
  89. self.operationQueue = [[NSOperationQueue alloc] init];
  90. self.operationQueue.maxConcurrentOperationCount = 3;
  91. }
  92. - (void)releaseObjs {
  93. for (UIView *sub in self.view.subviews) {
  94. [sub removeFromSuperview];
  95. }
  96. [self->_models removeAllObjects];
  97. self.collectionView = nil;
  98. self.imagePickerVc = nil;
  99. self.location = nil;
  100. [self.operationQueue cancelAllOperations];
  101. self.operationQueue = nil;
  102. }
  103. - (void)fetchAssetModels {
  104. TZImagePickerController *tzImagePickerVc = (TZImagePickerController *)self.navigationController;
  105. if (_isFirstAppear && !_model.models.count) {
  106. [tzImagePickerVc showProgressHUD];
  107. }
  108. dispatch_async(dispatch_get_global_queue(0, 0), ^{
  109. if (!tzImagePickerVc.sortAscendingByModificationDate && self->_isFirstAppear && self->_model.isCameraRoll) {
  110. [[TZImageManager manager] getCameraRollAlbum:tzImagePickerVc.allowPickingVideo allowPickingImage:tzImagePickerVc.allowPickingImage needFetchAssets:YES completion:^(TZAlbumModel *model) {
  111. self->_model = model;
  112. self->_models = [NSMutableArray arrayWithArray:self->_model.models];
  113. [self initSubviews];
  114. }];
  115. } else {
  116. if (self->_showTakePhotoBtn || self->_isFirstAppear) {
  117. [[TZImageManager manager] getAssetsFromFetchResult:self->_model.result completion:^(NSArray<TZAssetModel *> *models) {
  118. self->_models = [NSMutableArray arrayWithArray:models];
  119. [self initSubviews];
  120. }];
  121. } else {
  122. self->_models = [NSMutableArray arrayWithArray:self->_model.models];
  123. [self initSubviews];
  124. }
  125. }
  126. });
  127. }
  128. - (void)unCheckModel:(PHAsset *)asset {
  129. NSIndexPath *ip;
  130. for (NSInteger i = 0; i < _models.count; i++) {
  131. TZAssetModel *model = _models[i];
  132. if (model.asset == asset) {
  133. model.isChecked = NO;
  134. ip = [NSIndexPath indexPathForItem:i inSection:0];
  135. break;
  136. }
  137. }
  138. if (ip) {
  139. [self.collectionView reloadItemsAtIndexPaths:@[ip]];
  140. }
  141. }
  142. - (void)initSubviews {
  143. dispatch_async(dispatch_get_main_queue(), ^{
  144. TZImagePickerController *tzImagePickerVc = (TZImagePickerController *)self.navigationController;
  145. [tzImagePickerVc hideProgressHUD];
  146. [self checkSelectedModels];
  147. [self configCollectionView];
  148. self->_collectionView.hidden = YES;
  149. [self configBottomToolBar];
  150. [self scrollCollectionViewToBottom];
  151. });
  152. }
  153. - (void)viewWillDisappear:(BOOL)animated {
  154. [super viewWillDisappear:animated];
  155. TZImagePickerController *tzImagePickerVc = (TZImagePickerController *)self.navigationController;
  156. tzImagePickerVc.isSelectOriginalPhoto = _isSelectOriginalPhoto;
  157. }
  158. - (BOOL)prefersStatusBarHidden {
  159. return NO;
  160. }
  161. - (UIStatusBarStyle)preferredStatusBarStyle {
  162. TZImagePickerController *tzImagePicker = (TZImagePickerController *)self.navigationController;
  163. if (tzImagePicker && [tzImagePicker isKindOfClass:[TZImagePickerController class]]) {
  164. return tzImagePicker.statusBarStyle;
  165. }
  166. return [super preferredStatusBarStyle];
  167. }
  168. - (void)configCollectionView {
  169. _layout = [[UICollectionViewFlowLayout alloc] init];
  170. _collectionView = [[TZCollectionView alloc] initWithFrame:CGRectZero collectionViewLayout:_layout];
  171. _collectionView.backgroundColor = [UIColor whiteColor];
  172. _collectionView.dataSource = self;
  173. _collectionView.delegate = self;
  174. _collectionView.alwaysBounceHorizontal = NO;
  175. _collectionView.contentInset = UIEdgeInsetsMake(itemMargin, itemMargin, itemMargin, itemMargin);
  176. if (_showTakePhotoBtn) {
  177. _collectionView.contentSize = CGSizeMake(self.view.tz_width, ((_model.count + self.columnNumber) / self.columnNumber) * self.view.tz_width);
  178. } else {
  179. _collectionView.contentSize = CGSizeMake(self.view.tz_width, ((_model.count + self.columnNumber - 1) / self.columnNumber) * self.view.tz_width);
  180. if (_models.count == 0) {
  181. _noDataLabel = [UILabel new];
  182. _noDataLabel.textAlignment = NSTextAlignmentCenter;
  183. _noDataLabel.text = [NSBundle tz_localizedStringForKey:@"No Photos or Videos"];
  184. CGFloat rgb = 153 / 256.0;
  185. _noDataLabel.textColor = [UIColor colorWithRed:rgb green:rgb blue:rgb alpha:1.0];
  186. _noDataLabel.font = [UIFont boldSystemFontOfSize:20];
  187. [_collectionView addSubview:_noDataLabel];
  188. }
  189. }
  190. [self.view addSubview:_collectionView];
  191. [_collectionView registerClass:[TZAssetCell class] forCellWithReuseIdentifier:@"TZAssetCell"];
  192. [_collectionView registerClass:[TZAssetCameraCell class] forCellWithReuseIdentifier:@"TZAssetCameraCell"];
  193. }
  194. - (void)viewWillAppear:(BOOL)animated {
  195. [super viewWillAppear:animated];
  196. // Determine the size of the thumbnails to request from the PHCachingImageManager
  197. CGFloat scale = 2.0;
  198. if ([UIScreen mainScreen].bounds.size.width > 600) {
  199. scale = 1.0;
  200. }
  201. CGSize cellSize = ((UICollectionViewFlowLayout *)_collectionView.collectionViewLayout).itemSize;
  202. AssetGridThumbnailSize = CGSizeMake(cellSize.width * scale, cellSize.height * scale);
  203. if (!_models) {
  204. [self fetchAssetModels];
  205. }
  206. }
  207. - (void)viewDidAppear:(BOOL)animated {
  208. [super viewDidAppear:animated];
  209. // [self updateCachedAssets];
  210. UINavigationBar *bar = self.navigationController.navigationBar;
  211. if (bar.tz_top <= 0) {
  212. bar.tz_top = 20.0;
  213. }
  214. }
  215. - (void)configBottomToolBar {
  216. TZImagePickerController *tzImagePickerVc = (TZImagePickerController *)self.navigationController;
  217. if (!tzImagePickerVc.showSelectBtn) return;
  218. _bottomToolBar = [[UIView alloc] initWithFrame:CGRectZero];
  219. CGFloat rgb = 253 / 255.0;
  220. _bottomToolBar.backgroundColor = [UIColor colorWithRed:rgb green:rgb blue:rgb alpha:1.0];
  221. _previewButton = [UIButton buttonWithType:UIButtonTypeCustom];
  222. [_previewButton addTarget:self action:@selector(previewButtonClick) forControlEvents:UIControlEventTouchUpInside];
  223. _previewButton.titleLabel.font = [UIFont systemFontOfSize:16];
  224. [_previewButton setTitle:tzImagePickerVc.previewBtnTitleStr forState:UIControlStateNormal];
  225. [_previewButton setTitle:tzImagePickerVc.previewBtnTitleStr forState:UIControlStateDisabled];
  226. [_previewButton setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
  227. [_previewButton setTitleColor:[UIColor lightGrayColor] forState:UIControlStateDisabled];
  228. _previewButton.enabled = tzImagePickerVc.selectedModels.count;
  229. if (tzImagePickerVc.allowPickingOriginalPhoto) {
  230. _originalPhotoButton = [UIButton buttonWithType:UIButtonTypeCustom];
  231. _originalPhotoButton.imageEdgeInsets = UIEdgeInsetsMake(0, [TZCommonTools tz_isRightToLeftLayout] ? 10 : -10, 0, 0);
  232. [_originalPhotoButton addTarget:self action:@selector(originalPhotoButtonClick) forControlEvents:UIControlEventTouchUpInside];
  233. _originalPhotoButton.titleLabel.font = [UIFont systemFontOfSize:16];
  234. [_originalPhotoButton setTitle:tzImagePickerVc.fullImageBtnTitleStr forState:UIControlStateNormal];
  235. [_originalPhotoButton setTitle:tzImagePickerVc.fullImageBtnTitleStr forState:UIControlStateSelected];
  236. [_originalPhotoButton setTitleColor:[UIColor lightGrayColor] forState:UIControlStateNormal];
  237. [_originalPhotoButton setTitleColor:[UIColor blackColor] forState:UIControlStateSelected];
  238. [_originalPhotoButton setImage:tzImagePickerVc.photoOriginDefImage forState:UIControlStateNormal];
  239. [_originalPhotoButton setImage:tzImagePickerVc.photoOriginSelImage forState:UIControlStateSelected];
  240. _originalPhotoButton.imageView.clipsToBounds = YES;
  241. _originalPhotoButton.imageView.contentMode = UIViewContentModeScaleAspectFit;
  242. _originalPhotoButton.selected = _isSelectOriginalPhoto;
  243. _originalPhotoButton.enabled = tzImagePickerVc.selectedModels.count > 0;
  244. _originalPhotoLabel = [[UILabel alloc] init];
  245. _originalPhotoLabel.textAlignment = NSTextAlignmentLeft;
  246. _originalPhotoLabel.font = [UIFont systemFontOfSize:16];
  247. _originalPhotoLabel.textColor = [UIColor blackColor];
  248. if (_isSelectOriginalPhoto) [self getSelectedPhotoBytes];
  249. }
  250. _doneButton = [UIButton buttonWithType:UIButtonTypeCustom];
  251. _doneButton.titleLabel.font = [UIFont systemFontOfSize:16];
  252. [_doneButton addTarget:self action:@selector(doneButtonClick) forControlEvents:UIControlEventTouchUpInside];
  253. [_doneButton setTitle:tzImagePickerVc.doneBtnTitleStr forState:UIControlStateNormal];
  254. [_doneButton setTitle:tzImagePickerVc.doneBtnTitleStr forState:UIControlStateDisabled];
  255. [_doneButton setTitleColor:tzImagePickerVc.oKButtonTitleColorNormal forState:UIControlStateNormal];
  256. [_doneButton setTitleColor:tzImagePickerVc.oKButtonTitleColorDisabled forState:UIControlStateDisabled];
  257. _doneButton.enabled = tzImagePickerVc.selectedModels.count || tzImagePickerVc.alwaysEnableDoneBtn;
  258. _numberImageView = [[UIImageView alloc] initWithImage:tzImagePickerVc.photoNumberIconImage];
  259. _numberImageView.hidden = tzImagePickerVc.selectedModels.count <= 0;
  260. _numberImageView.clipsToBounds = YES;
  261. _numberImageView.contentMode = UIViewContentModeScaleAspectFit;
  262. _numberImageView.backgroundColor = [UIColor clearColor];
  263. _numberLabel = [[UILabel alloc] init];
  264. _numberLabel.font = [UIFont systemFontOfSize:15];
  265. _numberLabel.textColor = [UIColor whiteColor];
  266. _numberLabel.textAlignment = NSTextAlignmentCenter;
  267. _numberLabel.text = [NSString stringWithFormat:@"%zd",tzImagePickerVc.selectedModels.count];
  268. _numberLabel.hidden = tzImagePickerVc.selectedModels.count <= 0;
  269. _numberLabel.backgroundColor = [UIColor clearColor];
  270. _divideLine = [[UIView alloc] init];
  271. CGFloat rgb2 = 222 / 255.0;
  272. _divideLine.backgroundColor = [UIColor colorWithRed:rgb2 green:rgb2 blue:rgb2 alpha:1.0];
  273. [_bottomToolBar addSubview:_divideLine];
  274. [_bottomToolBar addSubview:_previewButton];
  275. [_bottomToolBar addSubview:_doneButton];
  276. [_bottomToolBar addSubview:_numberImageView];
  277. [_bottomToolBar addSubview:_numberLabel];
  278. [_bottomToolBar addSubview:_originalPhotoButton];
  279. [self.view addSubview:_bottomToolBar];
  280. [_originalPhotoButton addSubview:_originalPhotoLabel];
  281. if (tzImagePickerVc.photoPickerPageUIConfigBlock) {
  282. tzImagePickerVc.photoPickerPageUIConfigBlock(_collectionView, _bottomToolBar, _previewButton, _originalPhotoButton, _originalPhotoLabel, _doneButton, _numberImageView, _numberLabel, _divideLine);
  283. }
  284. }
  285. #pragma mark - Layout
  286. - (void)viewDidLayoutSubviews {
  287. [super viewDidLayoutSubviews];
  288. TZImagePickerController *tzImagePickerVc = (TZImagePickerController *)self.navigationController;
  289. CGFloat top = 0;
  290. CGFloat collectionViewHeight = 0;
  291. CGFloat naviBarHeight = self.navigationController.navigationBar.tz_height;
  292. BOOL isStatusBarHidden = [UIApplication sharedApplication].isStatusBarHidden;
  293. CGFloat toolBarHeight = [TZCommonTools tz_isIPhoneX] ? 50 + (83 - 49) : 50;
  294. if (self.navigationController.navigationBar.isTranslucent) {
  295. top = naviBarHeight;
  296. if (!isStatusBarHidden) top += [TZCommonTools tz_statusBarHeight];
  297. collectionViewHeight = tzImagePickerVc.showSelectBtn ? self.view.tz_height - toolBarHeight - top : self.view.tz_height - top;;
  298. } else {
  299. collectionViewHeight = tzImagePickerVc.showSelectBtn ? self.view.tz_height - toolBarHeight : self.view.tz_height;
  300. }
  301. _collectionView.frame = CGRectMake(0, top, self.view.tz_width, collectionViewHeight);
  302. _noDataLabel.frame = _collectionView.bounds;
  303. CGFloat itemWH = (self.view.tz_width - (self.columnNumber + 1) * itemMargin) / self.columnNumber;
  304. _layout.itemSize = CGSizeMake(itemWH, itemWH);
  305. _layout.minimumInteritemSpacing = itemMargin;
  306. _layout.minimumLineSpacing = itemMargin;
  307. [_collectionView setCollectionViewLayout:_layout];
  308. if (_offsetItemCount > 0) {
  309. CGFloat offsetY = _offsetItemCount * (_layout.itemSize.height + _layout.minimumLineSpacing);
  310. [_collectionView setContentOffset:CGPointMake(0, offsetY)];
  311. }
  312. CGFloat toolBarTop = 0;
  313. if (!self.navigationController.navigationBar.isHidden) {
  314. toolBarTop = self.view.tz_height - toolBarHeight;
  315. } else {
  316. CGFloat navigationHeight = naviBarHeight + [TZCommonTools tz_statusBarHeight];
  317. toolBarTop = self.view.tz_height - toolBarHeight - navigationHeight;
  318. }
  319. _bottomToolBar.frame = CGRectMake(0, toolBarTop, self.view.tz_width, toolBarHeight);
  320. CGFloat previewWidth = [tzImagePickerVc.previewBtnTitleStr boundingRectWithSize:CGSizeMake(CGFLOAT_MAX, CGFLOAT_MAX) options:NSStringDrawingUsesFontLeading attributes:@{NSFontAttributeName:[UIFont systemFontOfSize:16]} context:nil].size.width + 2;
  321. if (!tzImagePickerVc.allowPreview) {
  322. previewWidth = 0.0;
  323. }
  324. _previewButton.frame = CGRectMake(10, 3, previewWidth, 44);
  325. _previewButton.tz_width = !tzImagePickerVc.showSelectBtn ? 0 : previewWidth;
  326. if (tzImagePickerVc.allowPickingOriginalPhoto) {
  327. CGFloat fullImageWidth = [tzImagePickerVc.fullImageBtnTitleStr boundingRectWithSize:CGSizeMake(CGFLOAT_MAX, CGFLOAT_MAX) options:NSStringDrawingUsesFontLeading attributes:@{NSFontAttributeName:[UIFont systemFontOfSize:13]} context:nil].size.width;
  328. _originalPhotoButton.frame = CGRectMake(CGRectGetMaxX(_previewButton.frame), 0, fullImageWidth + 56, 50);
  329. _originalPhotoLabel.frame = CGRectMake(fullImageWidth + 46, 0, 80, 50);
  330. }
  331. [_doneButton sizeToFit];
  332. _doneButton.frame = CGRectMake(self.view.tz_width - _doneButton.tz_width - 12, 0, _doneButton.tz_width, 50);
  333. _numberImageView.frame = CGRectMake(_doneButton.tz_left - 24 - 5, 13, 24, 24);
  334. _numberLabel.frame = _numberImageView.frame;
  335. _divideLine.frame = CGRectMake(0, 0, self.view.tz_width, 1);
  336. [TZImageManager manager].columnNumber = [TZImageManager manager].columnNumber;
  337. [TZImageManager manager].photoWidth = tzImagePickerVc.photoWidth;
  338. [self.collectionView reloadData];
  339. if (tzImagePickerVc.photoPickerPageDidLayoutSubviewsBlock) {
  340. tzImagePickerVc.photoPickerPageDidLayoutSubviewsBlock(_collectionView, _bottomToolBar, _previewButton, _originalPhotoButton, _originalPhotoLabel, _doneButton, _numberImageView, _numberLabel, _divideLine);
  341. }
  342. }
  343. #pragma mark - Notification
  344. - (void)didChangeStatusBarOrientationNotification:(NSNotification *)noti {
  345. _offsetItemCount = _collectionView.contentOffset.y / (_layout.itemSize.height + _layout.minimumLineSpacing);
  346. }
  347. #pragma mark - Click Event
  348. - (void)navLeftBarButtonClick{
  349. [self.navigationController popViewControllerAnimated:YES];
  350. }
  351. - (void)previewButtonClick {
  352. TZPhotoPreviewController *photoPreviewVc = [[TZPhotoPreviewController alloc] init];
  353. [self pushPhotoPrevireViewController:photoPreviewVc needCheckSelectedModels:YES];
  354. }
  355. - (void)originalPhotoButtonClick {
  356. _originalPhotoButton.selected = !_originalPhotoButton.isSelected;
  357. _isSelectOriginalPhoto = _originalPhotoButton.isSelected;
  358. _originalPhotoLabel.hidden = !_originalPhotoButton.isSelected;
  359. if (_isSelectOriginalPhoto) {
  360. [self getSelectedPhotoBytes];
  361. }
  362. }
  363. - (void)doneButtonClick {
  364. TZImagePickerController *tzImagePickerVc = (TZImagePickerController *)self.navigationController;
  365. // 1.6.8 判断是否满足最小必选张数的限制
  366. if (tzImagePickerVc.minImagesCount && tzImagePickerVc.selectedModels.count < tzImagePickerVc.minImagesCount) {
  367. NSString *title = [NSString stringWithFormat:[NSBundle tz_localizedStringForKey:@"Select a minimum of %zd photos"], tzImagePickerVc.minImagesCount];
  368. [tzImagePickerVc showAlertWithTitle:title];
  369. return;
  370. }
  371. // [tzImagePickerVc showProgressHUD];
  372. NSMutableArray *assets = [NSMutableArray array];
  373. NSMutableArray *photos;
  374. NSMutableArray *infoArr;
  375. if (tzImagePickerVc.onlyReturnAsset) { // not fetch image
  376. for (NSInteger i = 0; i < tzImagePickerVc.selectedModels.count; i++) {
  377. TZAssetModel *model = tzImagePickerVc.selectedModels[i];
  378. [assets addObject:model.asset];
  379. }
  380. } else { // fetch image
  381. photos = [NSMutableArray array];
  382. infoArr = [NSMutableArray array];
  383. for (NSInteger i = 0; i < tzImagePickerVc.selectedModels.count; i++) { [photos addObject:@1];[assets addObject:@1];[infoArr addObject:@1]; }
  384. __block BOOL havenotShowAlert = YES;
  385. [TZImageManager manager].shouldFixOrientation = YES;
  386. __block UIAlertController *alertView;
  387. for (NSInteger i = 0; i < tzImagePickerVc.selectedModels.count; i++) {
  388. TZAssetModel *model = tzImagePickerVc.selectedModels[i];
  389. TZImageRequestOperation *operation = [[TZImageRequestOperation alloc] initWithAsset:model.asset completion:^(UIImage * _Nonnull photo, NSDictionary * _Nonnull info, BOOL isDegraded) {
  390. if (isDegraded) return;
  391. if (photo) {
  392. if (![TZImagePickerConfig sharedInstance].notScaleImage) {
  393. photo = [[TZImageManager manager] scaleImage:photo toSize:CGSizeMake(tzImagePickerVc.photoWidth, (int)(tzImagePickerVc.photoWidth * photo.size.height / photo.size.width))];
  394. }
  395. [photos replaceObjectAtIndex:i withObject:photo];
  396. }
  397. if (info) [infoArr replaceObjectAtIndex:i withObject:info];
  398. [assets replaceObjectAtIndex:i withObject:model.asset];
  399. for (id item in photos) { if ([item isKindOfClass:[NSNumber class]]) return; }
  400. if (havenotShowAlert) {
  401. [tzImagePickerVc hideAlertView:alertView];
  402. [self didGetAllPhotos:photos assets:assets infoArr:infoArr];
  403. }
  404. } progressHandler:^(double progress, NSError * _Nonnull error, BOOL * _Nonnull stop, NSDictionary * _Nonnull info) {
  405. // 如果图片正在从iCloud同步中,提醒用户
  406. if (progress < 1 && havenotShowAlert && !alertView) {
  407. [tzImagePickerVc hideProgressHUD];
  408. alertView = [tzImagePickerVc showAlertWithTitle:[NSBundle tz_localizedStringForKey:@"Synchronizing photos from iCloud"]];
  409. havenotShowAlert = NO;
  410. return;
  411. }
  412. if (progress >= 1) {
  413. havenotShowAlert = YES;
  414. }
  415. }];
  416. [self.operationQueue addOperation:operation];
  417. }
  418. }
  419. if (tzImagePickerVc.selectedModels.count <= 0 || tzImagePickerVc.onlyReturnAsset) {
  420. [self didGetAllPhotos:photos assets:assets infoArr:infoArr];
  421. }
  422. }
  423. - (void)didGetAllPhotos:(NSArray *)photos assets:(NSArray *)assets infoArr:(NSArray *)infoArr {
  424. TZImagePickerController *tzImagePickerVc = (TZImagePickerController *)self.navigationController;
  425. [tzImagePickerVc hideProgressHUD];
  426. if (tzImagePickerVc.autoDismiss) {
  427. [self.navigationController dismissViewControllerAnimated:YES completion:^{
  428. [self callDelegateMethodWithPhotos:photos assets:assets infoArr:infoArr];
  429. }];
  430. } else {
  431. [self callDelegateMethodWithPhotos:photos assets:assets infoArr:infoArr];
  432. }
  433. }
  434. - (void)callDelegateMethodWithPhotos:(NSArray *)photos assets:(NSArray *)assets infoArr:(NSArray *)infoArr {
  435. TZImagePickerController *tzImagePickerVc = (TZImagePickerController *)self.navigationController;
  436. if (tzImagePickerVc.allowPickingVideo && tzImagePickerVc.maxImagesCount == 1) {
  437. if ([[TZImageManager manager] isVideo:[assets firstObject]]) {
  438. if ([tzImagePickerVc.pickerDelegate respondsToSelector:@selector(imagePickerController:didFinishPickingVideo:sourceAssets:)]) {
  439. [tzImagePickerVc.pickerDelegate imagePickerController:tzImagePickerVc didFinishPickingVideo:[photos firstObject] sourceAssets:[assets firstObject]];
  440. }
  441. if (tzImagePickerVc.didFinishPickingVideoHandle) {
  442. tzImagePickerVc.didFinishPickingVideoHandle([photos firstObject], [assets firstObject]);
  443. }
  444. return;
  445. }
  446. }
  447. if ([tzImagePickerVc.pickerDelegate respondsToSelector:@selector(imagePickerController:didFinishPickingPhotos:sourceAssets:isSelectOriginalPhoto:)]) {
  448. [tzImagePickerVc.pickerDelegate imagePickerController:tzImagePickerVc didFinishPickingPhotos:photos sourceAssets:assets isSelectOriginalPhoto:_isSelectOriginalPhoto];
  449. }
  450. if ([tzImagePickerVc.pickerDelegate respondsToSelector:@selector(imagePickerController:didFinishPickingPhotos:sourceAssets:isSelectOriginalPhoto:infos:)]) {
  451. [tzImagePickerVc.pickerDelegate imagePickerController:tzImagePickerVc didFinishPickingPhotos:photos sourceAssets:assets isSelectOriginalPhoto:_isSelectOriginalPhoto infos:infoArr];
  452. }
  453. if (tzImagePickerVc.didFinishPickingPhotosHandle) {
  454. tzImagePickerVc.didFinishPickingPhotosHandle(photos,assets,_isSelectOriginalPhoto);
  455. }
  456. if (tzImagePickerVc.didFinishPickingPhotosWithInfosHandle) {
  457. tzImagePickerVc.didFinishPickingPhotosWithInfosHandle(photos,assets,_isSelectOriginalPhoto,infoArr);
  458. }
  459. }
  460. #pragma mark - UICollectionViewDataSource && Delegate
  461. - (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
  462. if (_showTakePhotoBtn) {
  463. return _models.count + 1;
  464. }
  465. return _models.count;
  466. }
  467. - (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
  468. // the cell lead to take a picture / 去拍照的cell
  469. TZImagePickerController *tzImagePickerVc = (TZImagePickerController *)self.navigationController;
  470. if (((tzImagePickerVc.sortAscendingByModificationDate && indexPath.item >= _models.count) || (!tzImagePickerVc.sortAscendingByModificationDate && indexPath.item == 0)) && _showTakePhotoBtn) {
  471. TZAssetCameraCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"TZAssetCameraCell" forIndexPath:indexPath];
  472. cell.imageView.image = tzImagePickerVc.takePictureImage;
  473. if ([tzImagePickerVc.takePictureImageName isEqualToString:@"takePicture80"]) {
  474. cell.imageView.contentMode = UIViewContentModeCenter;
  475. CGFloat rgb = 223 / 255.0;
  476. cell.imageView.backgroundColor = [UIColor colorWithRed:rgb green:rgb blue:rgb alpha:1.0];
  477. } else {
  478. cell.imageView.backgroundColor = [UIColor colorWithWhite:1.000 alpha:0.500];
  479. }
  480. return cell;
  481. }
  482. // the cell dipaly photo or video / 展示照片或视频的cell
  483. TZAssetCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"TZAssetCell" forIndexPath:indexPath];
  484. cell.allowPickingMultipleVideo = tzImagePickerVc.allowPickingMultipleVideo;
  485. cell.photoDefImage = tzImagePickerVc.photoDefImage;
  486. cell.photoSelImage = tzImagePickerVc.photoSelImage;
  487. cell.assetCellDidSetModelBlock = tzImagePickerVc.assetCellDidSetModelBlock;
  488. cell.assetCellDidLayoutSubviewsBlock = tzImagePickerVc.assetCellDidLayoutSubviewsBlock;
  489. TZAssetModel *model;
  490. if (tzImagePickerVc.sortAscendingByModificationDate || !_showTakePhotoBtn) {
  491. model = _models[indexPath.item];
  492. } else {
  493. model = _models[indexPath.item - 1];
  494. }
  495. cell.allowPickingGif = tzImagePickerVc.allowPickingGif;
  496. cell.model = model;
  497. if (model.isSelected && tzImagePickerVc.showSelectedIndex) {
  498. cell.index = [tzImagePickerVc.selectedAssetIds indexOfObject:model.asset.localIdentifier] + 1;
  499. }
  500. cell.showSelectBtn = tzImagePickerVc.showSelectBtn;
  501. cell.allowPreview = tzImagePickerVc.allowPreview;
  502. if (tzImagePickerVc.selectedModels.count >= tzImagePickerVc.maxImagesCount && tzImagePickerVc.showPhotoCannotSelectLayer && !model.isSelected) {
  503. cell.cannotSelectLayerButton.backgroundColor = tzImagePickerVc.cannotSelectLayerColor;
  504. cell.cannotSelectLayerButton.hidden = NO;
  505. } else {
  506. cell.cannotSelectLayerButton.hidden = YES;
  507. }
  508. __weak typeof(cell) weakCell = cell;
  509. __weak typeof(self) weakSelf = self;
  510. __weak typeof(_numberImageView.layer) weakLayer = _numberImageView.layer;
  511. cell.didSelectPhotoBlock = ^(BOOL isSelected) {
  512. __strong typeof(weakCell) strongCell = weakCell;
  513. __strong typeof(weakSelf) strongSelf = weakSelf;
  514. __strong typeof(weakLayer) strongLayer = weakLayer;
  515. TZImagePickerController *tzImagePickerVc = (TZImagePickerController *)strongSelf.navigationController;
  516. // 1. cancel select / 取消选择
  517. if (isSelected) {
  518. strongCell.selectPhotoButton.selected = NO;
  519. model.isSelected = NO;
  520. NSArray *selectedModels = [NSArray arrayWithArray:tzImagePickerVc.selectedModels];
  521. for (TZAssetModel *model_item in selectedModels) {
  522. if ([model.asset.localIdentifier isEqualToString:model_item.asset.localIdentifier]) {
  523. [tzImagePickerVc removeSelectedModel:model_item];
  524. break;
  525. }
  526. }
  527. [strongSelf refreshBottomToolBarStatus];
  528. if (tzImagePickerVc.showSelectedIndex || tzImagePickerVc.showPhotoCannotSelectLayer) {
  529. [[NSNotificationCenter defaultCenter] postNotificationName:@"TZ_PHOTO_PICKER_RELOAD_NOTIFICATION" object:strongSelf.navigationController];
  530. }
  531. [UIView showOscillatoryAnimationWithLayer:strongLayer type:TZOscillatoryAnimationToSmaller];
  532. } else {
  533. // 2. select:check if over the maxImagesCount / 选择照片,检查是否超过了最大个数的限制
  534. if (tzImagePickerVc.selectedModels.count < tzImagePickerVc.maxImagesCount) {
  535. if (tzImagePickerVc.maxImagesCount == 1 && !tzImagePickerVc.allowPreview) {
  536. model.isSelected = YES;
  537. [strongCell toggleCheck:YES];
  538. [tzImagePickerVc addSelectedModel:model];
  539. [strongSelf doneButtonClick];
  540. return;
  541. }
  542. strongCell.selectPhotoButton.selected = YES;
  543. model.isSelected = YES;
  544. [tzImagePickerVc addSelectedModel:model];
  545. if (tzImagePickerVc.showSelectedIndex || tzImagePickerVc.showPhotoCannotSelectLayer) {
  546. [[NSNotificationCenter defaultCenter] postNotificationName:@"TZ_PHOTO_PICKER_RELOAD_NOTIFICATION" object:strongSelf.navigationController];
  547. }
  548. [strongSelf refreshBottomToolBarStatus];
  549. [UIView showOscillatoryAnimationWithLayer:strongLayer type:TZOscillatoryAnimationToSmaller];
  550. } else {
  551. if (self.isSpotMode) {
  552. return;
  553. }
  554. NSString *title = [NSString stringWithFormat:[NSBundle tz_localizedStringForKey:@"Select a maximum of %zd photos"], tzImagePickerVc.maxImagesCount];
  555. [tzImagePickerVc showAlertWithTitle:title];
  556. }
  557. }
  558. };
  559. cell.didLongPressPhotoBlock = ^(TZAssetModel *model) {
  560. __strong typeof(weakCell) strongCell = weakCell;
  561. TZVideoPlayerController *videoPlayerVc = [[TZVideoPlayerController alloc] init];
  562. videoPlayerVc.currentCell = strongCell;
  563. [weakSelf.navigationController pushViewController:videoPlayerVc animated:YES];
  564. };
  565. return cell;
  566. }
  567. - (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
  568. // take a photo / 去拍照
  569. TZImagePickerController *tzImagePickerVc = (TZImagePickerController *)self.navigationController;
  570. if (((tzImagePickerVc.sortAscendingByModificationDate && indexPath.item >= _models.count) || (!tzImagePickerVc.sortAscendingByModificationDate && indexPath.item == 0)) && _showTakePhotoBtn) {
  571. [self takePhoto]; return;
  572. }
  573. // preview phote or video / 预览照片或视频
  574. NSInteger index = indexPath.item;
  575. if (!tzImagePickerVc.sortAscendingByModificationDate && _showTakePhotoBtn) {
  576. index = indexPath.item - 1;
  577. }
  578. TZAssetModel *model = _models[index];
  579. if (model.type == TZAssetModelMediaTypeVideo && !tzImagePickerVc.allowPickingMultipleVideo) {
  580. if (tzImagePickerVc.selectedModels.count > 0) {
  581. TZImagePickerController *imagePickerVc = (TZImagePickerController *)self.navigationController;
  582. [imagePickerVc showAlertWithTitle:[NSBundle tz_localizedStringForKey:@"Can not choose both video and photo"]];
  583. } else {
  584. /// 在Cell imageView中添加了longPress 手势来触发视频预览
  585. // TZVideoPlayerController *videoPlayerVc = [[TZVideoPlayerController alloc] init];
  586. // videoPlayerVc.model = model;
  587. // [self.navigationController pushViewController:videoPlayerVc animated:YES];
  588. }
  589. } else if (model.type == TZAssetModelMediaTypePhotoGif && tzImagePickerVc.allowPickingGif && !tzImagePickerVc.allowPickingMultipleVideo) {
  590. if (tzImagePickerVc.selectedModels.count > 0) {
  591. TZImagePickerController *imagePickerVc = (TZImagePickerController *)self.navigationController;
  592. [imagePickerVc showAlertWithTitle:[NSBundle tz_localizedStringForKey:@"Can not choose both photo and GIF"]];
  593. } else {
  594. TZGifPhotoPreviewController *gifPreviewVc = [[TZGifPhotoPreviewController alloc] init];
  595. gifPreviewVc.model = model;
  596. [self.navigationController pushViewController:gifPreviewVc animated:YES];
  597. }
  598. } else {
  599. TZPhotoPreviewController *photoPreviewVc = [[TZPhotoPreviewController alloc] init];
  600. photoPreviewVc.currentIndex = index;
  601. photoPreviewVc.models = _models;
  602. [self pushPhotoPrevireViewController:photoPreviewVc];
  603. }
  604. }
  605. #pragma mark - UIScrollViewDelegate
  606. - (void)scrollViewDidScroll:(UIScrollView *)scrollView {
  607. // [self updateCachedAssets];
  608. }
  609. #pragma mark - Private Method
  610. /// 拍照按钮点击事件
  611. - (void)takePhoto {
  612. AVAuthorizationStatus authStatus = [AVCaptureDevice authorizationStatusForMediaType:AVMediaTypeVideo];
  613. if ((authStatus == AVAuthorizationStatusRestricted || authStatus ==AVAuthorizationStatusDenied)) {
  614. NSDictionary *infoDict = [TZCommonTools tz_getInfoDictionary];
  615. // 无权限 做一个友好的提示
  616. NSString *appName = [infoDict valueForKey:@"CFBundleDisplayName"];
  617. if (!appName) appName = [infoDict valueForKey:@"CFBundleName"];
  618. NSString *message = [NSString stringWithFormat:[NSBundle tz_localizedStringForKey:@"Please allow %@ to access your camera in \"Settings -> Privacy -> Camera\""],appName];
  619. UIAlertView *alert = [[UIAlertView alloc] initWithTitle:[NSBundle tz_localizedStringForKey:@"Can not use camera"] message:message delegate:self cancelButtonTitle:[NSBundle tz_localizedStringForKey:@"Cancel"] otherButtonTitles:[NSBundle tz_localizedStringForKey:@"Setting"], nil];
  620. [alert show];
  621. } else if (authStatus == AVAuthorizationStatusNotDetermined) {
  622. // fix issue 466, 防止用户首次拍照拒绝授权时相机页黑屏
  623. [AVCaptureDevice requestAccessForMediaType:AVMediaTypeVideo completionHandler:^(BOOL granted) {
  624. if (granted) {
  625. dispatch_async(dispatch_get_main_queue(), ^{
  626. [self pushImagePickerController];
  627. });
  628. }
  629. }];
  630. } else {
  631. [self pushImagePickerController];
  632. }
  633. }
  634. // 调用相机
  635. - (void)pushImagePickerController {
  636. // 提前定位
  637. TZImagePickerController *tzImagePickerVc = (TZImagePickerController *)self.navigationController;
  638. if (tzImagePickerVc.allowCameraLocation) {
  639. __weak typeof(self) weakSelf = self;
  640. [[TZLocationManager manager] startLocationWithSuccessBlock:^(NSArray<CLLocation *> *locations) {
  641. __strong typeof(weakSelf) strongSelf = weakSelf;
  642. strongSelf.location = [locations firstObject];
  643. } failureBlock:^(NSError *error) {
  644. __strong typeof(weakSelf) strongSelf = weakSelf;
  645. strongSelf.location = nil;
  646. }];
  647. }
  648. UIImagePickerControllerSourceType sourceType = UIImagePickerControllerSourceTypeCamera;
  649. if ([UIImagePickerController isSourceTypeAvailable: sourceType]) {
  650. self.imagePickerVc.sourceType = sourceType;
  651. NSMutableArray *mediaTypes = [NSMutableArray array];
  652. if (tzImagePickerVc.allowTakePicture) {
  653. [mediaTypes addObject:(NSString *)kUTTypeImage];
  654. }
  655. if (tzImagePickerVc.allowTakeVideo) {
  656. [mediaTypes addObject:(NSString *)kUTTypeMovie];
  657. self.imagePickerVc.videoMaximumDuration = tzImagePickerVc.videoMaximumDuration;
  658. }
  659. self.imagePickerVc.mediaTypes= mediaTypes;
  660. if (tzImagePickerVc.uiImagePickerControllerSettingBlock) {
  661. tzImagePickerVc.uiImagePickerControllerSettingBlock(_imagePickerVc);
  662. }
  663. [self presentViewController:_imagePickerVc animated:YES completion:nil];
  664. } else {
  665. NSLog(@"模拟器中无法打开照相机,请在真机中使用");
  666. }
  667. }
  668. - (void)refreshBottomToolBarStatus {
  669. TZImagePickerController *tzImagePickerVc = (TZImagePickerController *)self.navigationController;
  670. _previewButton.enabled = tzImagePickerVc.selectedModels.count > 0;
  671. _doneButton.enabled = tzImagePickerVc.selectedModels.count > 0 || tzImagePickerVc.alwaysEnableDoneBtn;
  672. _numberImageView.hidden = tzImagePickerVc.selectedModels.count <= 0;
  673. _numberLabel.hidden = tzImagePickerVc.selectedModels.count <= 0;
  674. _numberLabel.text = [NSString stringWithFormat:@"%zd",tzImagePickerVc.selectedModels.count];
  675. _originalPhotoButton.enabled = tzImagePickerVc.selectedModels.count > 0;
  676. _originalPhotoButton.selected = (_isSelectOriginalPhoto && _originalPhotoButton.enabled);
  677. _originalPhotoLabel.hidden = (!_originalPhotoButton.isSelected);
  678. if (_isSelectOriginalPhoto) [self getSelectedPhotoBytes];
  679. if (tzImagePickerVc.photoPickerPageDidRefreshStateBlock) {
  680. tzImagePickerVc.photoPickerPageDidRefreshStateBlock(_collectionView, _bottomToolBar, _previewButton, _originalPhotoButton, _originalPhotoLabel, _doneButton, _numberImageView, _numberLabel, _divideLine);;
  681. }
  682. }
  683. - (void)pushPhotoPrevireViewController:(TZPhotoPreviewController *)photoPreviewVc {
  684. [self pushPhotoPrevireViewController:photoPreviewVc needCheckSelectedModels:NO];
  685. }
  686. - (void)pushPhotoPrevireViewController:(TZPhotoPreviewController *)photoPreviewVc needCheckSelectedModels:(BOOL)needCheckSelectedModels {
  687. __weak typeof(self) weakSelf = self;
  688. photoPreviewVc.isSelectOriginalPhoto = _isSelectOriginalPhoto;
  689. [photoPreviewVc setBackButtonClickBlock:^(BOOL isSelectOriginalPhoto) {
  690. __strong typeof(weakSelf) strongSelf = weakSelf;
  691. strongSelf.isSelectOriginalPhoto = isSelectOriginalPhoto;
  692. if (needCheckSelectedModels) {
  693. [strongSelf checkSelectedModels];
  694. }
  695. [strongSelf.collectionView reloadData];
  696. [strongSelf refreshBottomToolBarStatus];
  697. }];
  698. [photoPreviewVc setDoneButtonClickBlock:^(BOOL isSelectOriginalPhoto) {
  699. __strong typeof(weakSelf) strongSelf = weakSelf;
  700. strongSelf.isSelectOriginalPhoto = isSelectOriginalPhoto;
  701. [strongSelf doneButtonClick];
  702. }];
  703. [photoPreviewVc setDoneButtonClickBlockCropMode:^(UIImage *cropedImage, id asset) {
  704. __strong typeof(weakSelf) strongSelf = weakSelf;
  705. [strongSelf didGetAllPhotos:@[cropedImage] assets:@[asset] infoArr:nil];
  706. }];
  707. [self.navigationController pushViewController:photoPreviewVc animated:YES];
  708. }
  709. - (void)getSelectedPhotoBytes {
  710. // 越南语 && 5屏幕时会显示不下,暂时这样处理
  711. if ([[TZImagePickerConfig sharedInstance].preferredLanguage isEqualToString:@"vi"] && self.view.tz_width <= 320) {
  712. return;
  713. }
  714. TZImagePickerController *imagePickerVc = (TZImagePickerController *)self.navigationController;
  715. [[TZImageManager manager] getPhotosBytesWithArray:imagePickerVc.selectedModels completion:^(NSString *totalBytes) {
  716. self->_originalPhotoLabel.text = [NSString stringWithFormat:@"(%@)",totalBytes];
  717. }];
  718. }
  719. - (void)scrollCollectionViewToBottom {
  720. TZImagePickerController *tzImagePickerVc = (TZImagePickerController *)self.navigationController;
  721. if (_shouldScrollToBottom && _models.count > 0) {
  722. NSInteger item = 0;
  723. if (tzImagePickerVc.sortAscendingByModificationDate) {
  724. item = _models.count - 1;
  725. if (_showTakePhotoBtn) {
  726. item += 1;
  727. }
  728. }
  729. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.01 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
  730. [self->_collectionView scrollToItemAtIndexPath:[NSIndexPath indexPathForItem:item inSection:0] atScrollPosition:UICollectionViewScrollPositionBottom animated:NO];
  731. self->_shouldScrollToBottom = NO;
  732. self->_collectionView.hidden = NO;
  733. });
  734. } else {
  735. _collectionView.hidden = NO;
  736. }
  737. }
  738. - (void)checkSelectedModels {
  739. NSMutableArray *selectedAssets = [NSMutableArray array];
  740. TZImagePickerController *tzImagePickerVc = (TZImagePickerController *)self.navigationController;
  741. for (TZAssetModel *model in tzImagePickerVc.selectedModels) {
  742. [selectedAssets addObject:model.asset];
  743. }
  744. for (TZAssetModel *model in _models) {
  745. model.isSelected = NO;
  746. if ([selectedAssets containsObject:model.asset]) {
  747. model.isSelected = YES;
  748. }
  749. }
  750. }
  751. #pragma mark - UIAlertViewDelegate
  752. - (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex {
  753. if (buttonIndex == 1) { // 去设置界面,开启相机访问权限
  754. [[UIApplication sharedApplication] openURL:[NSURL URLWithString:UIApplicationOpenSettingsURLString]];
  755. }
  756. }
  757. #pragma mark - UIImagePickerControllerDelegate
  758. - (void)imagePickerController:(UIImagePickerController*)picker didFinishPickingMediaWithInfo:(NSDictionary *)info {
  759. [picker dismissViewControllerAnimated:YES completion:nil];
  760. NSString *type = [info objectForKey:UIImagePickerControllerMediaType];
  761. if ([type isEqualToString:@"public.image"]) {
  762. // TZImagePickerController *imagePickerVc = (TZImagePickerController *)self.navigationController;
  763. // [imagePickerVc showProgressHUD];
  764. UIImage *photo = [info objectForKey:UIImagePickerControllerOriginalImage];
  765. if (photo) {
  766. [[TZImageManager manager] savePhotoWithImage:photo location:self.location completion:^(PHAsset *asset, NSError *error){
  767. if (!error) {
  768. [self addPHAsset:asset];
  769. }
  770. }];
  771. self.location = nil;
  772. }
  773. } else if ([type isEqualToString:@"public.movie"]) {
  774. // TZImagePickerController *imagePickerVc = (TZImagePickerController *)self.navigationController;
  775. // [imagePickerVc showProgressHUD];
  776. NSURL *videoUrl = [info objectForKey:UIImagePickerControllerMediaURL];
  777. if (videoUrl) {
  778. [[TZImageManager manager] saveVideoWithUrl:videoUrl location:self.location completion:^(PHAsset *asset, NSError *error) {
  779. if (!error) {
  780. [self addPHAsset:asset];
  781. }
  782. }];
  783. self.location = nil;
  784. }
  785. }
  786. }
  787. - (void)addPHAsset:(PHAsset *)asset {
  788. TZAssetModel *assetModel = [[TZImageManager manager] createModelWithAsset:asset];
  789. TZImagePickerController *tzImagePickerVc = (TZImagePickerController *)self.navigationController;
  790. [tzImagePickerVc hideProgressHUD];
  791. if (tzImagePickerVc.sortAscendingByModificationDate) {
  792. [_models addObject:assetModel];
  793. } else {
  794. [_models insertObject:assetModel atIndex:0];
  795. }
  796. if (tzImagePickerVc.maxImagesCount <= 1) {
  797. if (tzImagePickerVc.allowCrop && asset.mediaType == PHAssetMediaTypeImage) {
  798. TZPhotoPreviewController *photoPreviewVc = [[TZPhotoPreviewController alloc] init];
  799. if (tzImagePickerVc.sortAscendingByModificationDate) {
  800. photoPreviewVc.currentIndex = _models.count - 1;
  801. } else {
  802. photoPreviewVc.currentIndex = 0;
  803. }
  804. photoPreviewVc.models = _models;
  805. [self pushPhotoPrevireViewController:photoPreviewVc];
  806. } else {
  807. [tzImagePickerVc addSelectedModel:assetModel];
  808. [self doneButtonClick];
  809. }
  810. return;
  811. }
  812. if (tzImagePickerVc.selectedModels.count < tzImagePickerVc.maxImagesCount) {
  813. if (assetModel.type == TZAssetModelMediaTypeVideo && !tzImagePickerVc.allowPickingMultipleVideo) {
  814. // 不能多选视频的情况下,不选中拍摄的视频
  815. } else {
  816. assetModel.isSelected = YES;
  817. [tzImagePickerVc addSelectedModel:assetModel];
  818. [self refreshBottomToolBarStatus];
  819. }
  820. }
  821. _collectionView.hidden = YES;
  822. [_collectionView reloadData];
  823. _shouldScrollToBottom = YES;
  824. [self scrollCollectionViewToBottom];
  825. }
  826. - (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker {
  827. [picker dismissViewControllerAnimated:YES completion:nil];
  828. }
  829. - (void)dealloc {
  830. NSLog(@"#🐣#: release %@", [self class]);
  831. }
  832. #pragma mark - Asset Caching
  833. - (void)resetCachedAssets {
  834. [[TZImageManager manager].cachingImageManager stopCachingImagesForAllAssets];
  835. self.previousPreheatRect = CGRectZero;
  836. }
  837. - (void)updateCachedAssets {
  838. BOOL isViewVisible = [self isViewLoaded] && [[self view] window] != nil;
  839. if (!isViewVisible) { return; }
  840. // The preheat window is twice the height of the visible rect.
  841. CGRect preheatRect = _collectionView.bounds;
  842. preheatRect = CGRectInset(preheatRect, 0.0f, -0.5f * CGRectGetHeight(preheatRect));
  843. /*
  844. Check if the collection view is showing an area that is significantly
  845. different to the last preheated area.
  846. */
  847. CGFloat delta = ABS(CGRectGetMidY(preheatRect) - CGRectGetMidY(self.previousPreheatRect));
  848. if (delta > CGRectGetHeight(_collectionView.bounds) / 3.0f) {
  849. // Compute the assets to start caching and to stop caching.
  850. NSMutableArray *addedIndexPaths = [NSMutableArray array];
  851. NSMutableArray *removedIndexPaths = [NSMutableArray array];
  852. [self computeDifferenceBetweenRect:self.previousPreheatRect andRect:preheatRect removedHandler:^(CGRect removedRect) {
  853. NSArray *indexPaths = [self aapl_indexPathsForElementsInRect:removedRect];
  854. [removedIndexPaths addObjectsFromArray:indexPaths];
  855. } addedHandler:^(CGRect addedRect) {
  856. NSArray *indexPaths = [self aapl_indexPathsForElementsInRect:addedRect];
  857. [addedIndexPaths addObjectsFromArray:indexPaths];
  858. }];
  859. NSArray *assetsToStartCaching = [self assetsAtIndexPaths:addedIndexPaths];
  860. NSArray *assetsToStopCaching = [self assetsAtIndexPaths:removedIndexPaths];
  861. // Update the assets the PHCachingImageManager is caching.
  862. [[TZImageManager manager].cachingImageManager startCachingImagesForAssets:assetsToStartCaching
  863. targetSize:AssetGridThumbnailSize
  864. contentMode:PHImageContentModeAspectFill
  865. options:nil];
  866. [[TZImageManager manager].cachingImageManager stopCachingImagesForAssets:assetsToStopCaching
  867. targetSize:AssetGridThumbnailSize
  868. contentMode:PHImageContentModeAspectFill
  869. options:nil];
  870. // Store the preheat rect to compare against in the future.
  871. self.previousPreheatRect = preheatRect;
  872. }
  873. }
  874. - (void)computeDifferenceBetweenRect:(CGRect)oldRect andRect:(CGRect)newRect removedHandler:(void (^)(CGRect removedRect))removedHandler addedHandler:(void (^)(CGRect addedRect))addedHandler {
  875. if (CGRectIntersectsRect(newRect, oldRect)) {
  876. CGFloat oldMaxY = CGRectGetMaxY(oldRect);
  877. CGFloat oldMinY = CGRectGetMinY(oldRect);
  878. CGFloat newMaxY = CGRectGetMaxY(newRect);
  879. CGFloat newMinY = CGRectGetMinY(newRect);
  880. if (newMaxY > oldMaxY) {
  881. CGRect rectToAdd = CGRectMake(newRect.origin.x, oldMaxY, newRect.size.width, (newMaxY - oldMaxY));
  882. addedHandler(rectToAdd);
  883. }
  884. if (oldMinY > newMinY) {
  885. CGRect rectToAdd = CGRectMake(newRect.origin.x, newMinY, newRect.size.width, (oldMinY - newMinY));
  886. addedHandler(rectToAdd);
  887. }
  888. if (newMaxY < oldMaxY) {
  889. CGRect rectToRemove = CGRectMake(newRect.origin.x, newMaxY, newRect.size.width, (oldMaxY - newMaxY));
  890. removedHandler(rectToRemove);
  891. }
  892. if (oldMinY < newMinY) {
  893. CGRect rectToRemove = CGRectMake(newRect.origin.x, oldMinY, newRect.size.width, (newMinY - oldMinY));
  894. removedHandler(rectToRemove);
  895. }
  896. } else {
  897. addedHandler(newRect);
  898. removedHandler(oldRect);
  899. }
  900. }
  901. - (NSArray *)assetsAtIndexPaths:(NSArray *)indexPaths {
  902. if (indexPaths.count == 0) { return nil; }
  903. NSMutableArray *assets = [NSMutableArray arrayWithCapacity:indexPaths.count];
  904. for (NSIndexPath *indexPath in indexPaths) {
  905. if (indexPath.item < _models.count) {
  906. TZAssetModel *model = _models[indexPath.item];
  907. [assets addObject:model.asset];
  908. }
  909. }
  910. return assets;
  911. }
  912. - (NSArray *)aapl_indexPathsForElementsInRect:(CGRect)rect {
  913. NSArray *allLayoutAttributes = [_collectionView.collectionViewLayout layoutAttributesForElementsInRect:rect];
  914. if (allLayoutAttributes.count == 0) { return nil; }
  915. NSMutableArray *indexPaths = [NSMutableArray arrayWithCapacity:allLayoutAttributes.count];
  916. for (UICollectionViewLayoutAttributes *layoutAttributes in allLayoutAttributes) {
  917. NSIndexPath *indexPath = layoutAttributes.indexPath;
  918. [indexPaths addObject:indexPath];
  919. }
  920. return indexPaths;
  921. }
  922. #pragma clang diagnostic pop
  923. @end
  924. @implementation TZCollectionView
  925. - (BOOL)touchesShouldCancelInContentView:(UIView *)view {
  926. if ([view isKindOfClass:[UIControl class]]) {
  927. return YES;
  928. }
  929. return [super touchesShouldCancelInContentView:view];
  930. }
  931. - (void)dealloc {
  932. NSLog(@"🐣release🐣: TZCollectionView ==== %@", self);
  933. }
  934. @end