TZPhotoPickerController.m 38 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783
  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. @interface TZPhotoPickerController ()<UICollectionViewDataSource,UICollectionViewDelegate,UIImagePickerControllerDelegate,UINavigationControllerDelegate,UIAlertViewDelegate> {
  18. NSMutableArray *_models;
  19. UIButton *_previewButton;
  20. UIButton *_doneButton;
  21. UIImageView *_numberImageView;
  22. UILabel *_numberLabel;
  23. UIButton *_originalPhotoButton;
  24. UILabel *_originalPhotoLabel;
  25. BOOL _shouldScrollToBottom;
  26. BOOL _showTakePhotoBtn;
  27. }
  28. @property CGRect previousPreheatRect;
  29. @property (nonatomic, assign) BOOL isSelectOriginalPhoto;
  30. @property (nonatomic, strong) TZCollectionView *collectionView;
  31. @property (nonatomic, strong) UIImagePickerController *imagePickerVc;
  32. @end
  33. static CGSize AssetGridThumbnailSize;
  34. @implementation TZPhotoPickerController
  35. #pragma clang diagnostic push
  36. #pragma clang diagnostic ignored "-Wdeprecated-declarations"
  37. - (UIImagePickerController *)imagePickerVc {
  38. if (_imagePickerVc == nil) {
  39. _imagePickerVc = [[UIImagePickerController alloc] init];
  40. _imagePickerVc.delegate = self;
  41. // set appearance / 改变相册选择页的导航栏外观
  42. _imagePickerVc.navigationBar.barTintColor = self.navigationController.navigationBar.barTintColor;
  43. _imagePickerVc.navigationBar.tintColor = self.navigationController.navigationBar.tintColor;
  44. UIBarButtonItem *tzBarItem, *BarItem;
  45. if (iOS9Later) {
  46. tzBarItem = [UIBarButtonItem appearanceWhenContainedInInstancesOfClasses:@[[TZImagePickerController class]]];
  47. BarItem = [UIBarButtonItem appearanceWhenContainedInInstancesOfClasses:@[[UIImagePickerController class]]];
  48. } else {
  49. tzBarItem = [UIBarButtonItem appearanceWhenContainedIn:[TZImagePickerController class], nil];
  50. BarItem = [UIBarButtonItem appearanceWhenContainedIn:[UIImagePickerController class], nil];
  51. }
  52. NSDictionary *titleTextAttributes = [tzBarItem titleTextAttributesForState:UIControlStateNormal];
  53. [BarItem setTitleTextAttributes:titleTextAttributes forState:UIControlStateNormal];
  54. }
  55. return _imagePickerVc;
  56. }
  57. - (void)viewDidLoad {
  58. [super viewDidLoad];
  59. TZImagePickerController *tzImagePickerVc = (TZImagePickerController *)self.navigationController;
  60. _isSelectOriginalPhoto = tzImagePickerVc.isSelectOriginalPhoto;
  61. _shouldScrollToBottom = YES;
  62. self.view.backgroundColor = [UIColor whiteColor];
  63. self.navigationItem.title = _model.name;
  64. self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:tzImagePickerVc.cancelBtnTitleStr style:UIBarButtonItemStylePlain target:tzImagePickerVc action:@selector(cancelButtonClick)];
  65. _showTakePhotoBtn = (([[TZImageManager manager] isCameraRollAlbum:_model.name]) && tzImagePickerVc.allowTakePicture);
  66. if (!tzImagePickerVc.sortAscendingByModificationDate && _isFirstAppear && iOS8Later) {
  67. [[TZImageManager manager] getCameraRollAlbum:tzImagePickerVc.allowPickingVideo allowPickingImage:tzImagePickerVc.allowPickingImage completion:^(TZAlbumModel *model) {
  68. _model = model;
  69. _models = [NSMutableArray arrayWithArray:_model.models];
  70. [self initSubviews];
  71. }];
  72. } else {
  73. if (_showTakePhotoBtn || !iOS8Later || _isFirstAppear) {
  74. [[TZImageManager manager] getAssetsFromFetchResult:_model.result allowPickingVideo:tzImagePickerVc.allowPickingVideo allowPickingImage:tzImagePickerVc.allowPickingImage completion:^(NSArray<TZAssetModel *> *models) {
  75. _models = [NSMutableArray arrayWithArray:models];
  76. [self initSubviews];
  77. }];
  78. } else {
  79. _models = [NSMutableArray arrayWithArray:_model.models];
  80. [self initSubviews];
  81. }
  82. }
  83. // [self resetCachedAssets];
  84. }
  85. - (void)initSubviews {
  86. [self checkSelectedModels];
  87. [self configCollectionView];
  88. [self configBottomToolBar];
  89. }
  90. - (void)viewWillDisappear:(BOOL)animated {
  91. [super viewWillDisappear:animated];
  92. TZImagePickerController *tzImagePickerVc = (TZImagePickerController *)self.navigationController;
  93. tzImagePickerVc.isSelectOriginalPhoto = _isSelectOriginalPhoto;
  94. if (self.backButtonClickHandle) {
  95. self.backButtonClickHandle(_model);
  96. }
  97. }
  98. - (BOOL)prefersStatusBarHidden {
  99. return NO;
  100. }
  101. - (void)configCollectionView {
  102. TZImagePickerController *tzImagePickerVc = (TZImagePickerController *)self.navigationController;
  103. UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init];
  104. CGFloat margin = 5;
  105. CGFloat itemWH = (self.view.tz_width - (self.columnNumber + 1) * margin) / self.columnNumber;
  106. layout.itemSize = CGSizeMake(itemWH, itemWH);
  107. layout.minimumInteritemSpacing = margin;
  108. layout.minimumLineSpacing = margin;
  109. CGFloat top = 0;
  110. CGFloat collectionViewHeight = 0;
  111. if (self.navigationController.navigationBar.isTranslucent) {
  112. top = 44;
  113. if (iOS7Later) top += 20;
  114. collectionViewHeight = tzImagePickerVc.showSelectBtn ? self.view.tz_height - 50 - top : self.view.tz_height - top;;
  115. } else {
  116. CGFloat navigationHeight = 44;
  117. if (iOS7Later) navigationHeight += 20;
  118. collectionViewHeight = tzImagePickerVc.showSelectBtn ? self.view.tz_height - 50 - navigationHeight : self.view.tz_height - navigationHeight;
  119. }
  120. _collectionView = [[TZCollectionView alloc] initWithFrame:CGRectMake(0, top, self.view.tz_width, collectionViewHeight) collectionViewLayout:layout];
  121. _collectionView.backgroundColor = [UIColor whiteColor];
  122. _collectionView.dataSource = self;
  123. _collectionView.delegate = self;
  124. _collectionView.alwaysBounceHorizontal = NO;
  125. _collectionView.contentInset = UIEdgeInsetsMake(margin, margin, margin, margin);
  126. if (_showTakePhotoBtn && tzImagePickerVc.allowTakePicture ) {
  127. _collectionView.contentSize = CGSizeMake(self.view.tz_width, ((_model.count + self.columnNumber) / self.columnNumber) * self.view.tz_width);
  128. } else {
  129. _collectionView.contentSize = CGSizeMake(self.view.tz_width, ((_model.count + self.columnNumber - 1) / self.columnNumber) * self.view.tz_width);
  130. }
  131. [self.view addSubview:_collectionView];
  132. [_collectionView registerClass:[TZAssetCell class] forCellWithReuseIdentifier:@"TZAssetCell"];
  133. [_collectionView registerClass:[TZAssetCameraCell class] forCellWithReuseIdentifier:@"TZAssetCameraCell"];
  134. }
  135. - (void)viewWillAppear:(BOOL)animated {
  136. [super viewWillAppear:animated];
  137. [self scrollCollectionViewToBottom];
  138. // Determine the size of the thumbnails to request from the PHCachingImageManager
  139. CGFloat scale = 2.0;
  140. if ([UIScreen mainScreen].bounds.size.width > 600) {
  141. scale = 1.0;
  142. }
  143. CGSize cellSize = ((UICollectionViewFlowLayout *)_collectionView.collectionViewLayout).itemSize;
  144. AssetGridThumbnailSize = CGSizeMake(cellSize.width * scale, cellSize.height * scale);
  145. }
  146. - (void)viewDidAppear:(BOOL)animated {
  147. [super viewDidAppear:animated];
  148. if (iOS8Later) {
  149. // [self updateCachedAssets];
  150. }
  151. }
  152. - (void)configBottomToolBar {
  153. TZImagePickerController *tzImagePickerVc = (TZImagePickerController *)self.navigationController;
  154. if (!tzImagePickerVc.showSelectBtn) return;
  155. CGFloat yOffset = 0;
  156. if (self.navigationController.navigationBar.isTranslucent) {
  157. yOffset = self.view.tz_height - 50;
  158. } else {
  159. CGFloat navigationHeight = 44;
  160. if (iOS7Later) navigationHeight += 20;
  161. yOffset = self.view.tz_height - 50 - navigationHeight;
  162. }
  163. UIView *bottomToolBar = [[UIView alloc] initWithFrame:CGRectMake(0, yOffset, self.view.tz_width, 50)];
  164. CGFloat rgb = 253 / 255.0;
  165. bottomToolBar.backgroundColor = [UIColor colorWithRed:rgb green:rgb blue:rgb alpha:1.0];
  166. CGFloat previewWidth = [tzImagePickerVc.previewBtnTitleStr boundingRectWithSize:CGSizeMake(CGFLOAT_MAX, CGFLOAT_MAX) options:NSStringDrawingUsesFontLeading attributes:@{NSFontAttributeName:[UIFont systemFontOfSize:16]} context:nil].size.width + 2;
  167. if (!tzImagePickerVc.allowPreview) {
  168. previewWidth = 0.0;
  169. }
  170. _previewButton = [UIButton buttonWithType:UIButtonTypeCustom];
  171. _previewButton.frame = CGRectMake(10, 3, previewWidth, 44);
  172. _previewButton.tz_width = !tzImagePickerVc.showSelectBtn ? 0 : previewWidth;
  173. [_previewButton addTarget:self action:@selector(previewButtonClick) forControlEvents:UIControlEventTouchUpInside];
  174. _previewButton.titleLabel.font = [UIFont systemFontOfSize:16];
  175. [_previewButton setTitle:tzImagePickerVc.previewBtnTitleStr forState:UIControlStateNormal];
  176. [_previewButton setTitle:tzImagePickerVc.previewBtnTitleStr forState:UIControlStateDisabled];
  177. [_previewButton setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
  178. [_previewButton setTitleColor:[UIColor lightGrayColor] forState:UIControlStateDisabled];
  179. _previewButton.enabled = tzImagePickerVc.selectedModels.count;
  180. if (tzImagePickerVc.allowPickingOriginalPhoto) {
  181. CGFloat fullImageWidth = [tzImagePickerVc.fullImageBtnTitleStr boundingRectWithSize:CGSizeMake(CGFLOAT_MAX, CGFLOAT_MAX) options:NSStringDrawingUsesFontLeading attributes:@{NSFontAttributeName:[UIFont systemFontOfSize:13]} context:nil].size.width;
  182. _originalPhotoButton = [UIButton buttonWithType:UIButtonTypeCustom];
  183. _originalPhotoButton.frame = CGRectMake(CGRectGetMaxX(_previewButton.frame), self.view.tz_height - 50, fullImageWidth + 56, 50);
  184. _originalPhotoButton.imageEdgeInsets = UIEdgeInsetsMake(0, -10, 0, 0);
  185. [_originalPhotoButton addTarget:self action:@selector(originalPhotoButtonClick) forControlEvents:UIControlEventTouchUpInside];
  186. _originalPhotoButton.titleLabel.font = [UIFont systemFontOfSize:16];
  187. [_originalPhotoButton setTitle:tzImagePickerVc.fullImageBtnTitleStr forState:UIControlStateNormal];
  188. [_originalPhotoButton setTitle:tzImagePickerVc.fullImageBtnTitleStr forState:UIControlStateSelected];
  189. [_originalPhotoButton setTitleColor:[UIColor lightGrayColor] forState:UIControlStateNormal];
  190. [_originalPhotoButton setTitleColor:[UIColor blackColor] forState:UIControlStateSelected];
  191. [_originalPhotoButton setImage:[UIImage imageNamedFromMyBundle:tzImagePickerVc.photoOriginDefImageName] forState:UIControlStateNormal];
  192. [_originalPhotoButton setImage:[UIImage imageNamedFromMyBundle:tzImagePickerVc.photoOriginSelImageName] forState:UIControlStateSelected];
  193. _originalPhotoButton.selected = _isSelectOriginalPhoto;
  194. _originalPhotoButton.enabled = tzImagePickerVc.selectedModels.count > 0;
  195. _originalPhotoLabel = [[UILabel alloc] init];
  196. _originalPhotoLabel.frame = CGRectMake(fullImageWidth + 46, 0, 80, 50);
  197. _originalPhotoLabel.textAlignment = NSTextAlignmentLeft;
  198. _originalPhotoLabel.font = [UIFont systemFontOfSize:16];
  199. _originalPhotoLabel.textColor = [UIColor blackColor];
  200. if (_isSelectOriginalPhoto) [self getSelectedPhotoBytes];
  201. }
  202. _doneButton = [UIButton buttonWithType:UIButtonTypeCustom];
  203. _doneButton.frame = CGRectMake(self.view.tz_width - 44 - 12, 3, 44, 44);
  204. _doneButton.titleLabel.font = [UIFont systemFontOfSize:16];
  205. [_doneButton addTarget:self action:@selector(doneButtonClick) forControlEvents:UIControlEventTouchUpInside];
  206. [_doneButton setTitle:tzImagePickerVc.doneBtnTitleStr forState:UIControlStateNormal];
  207. [_doneButton setTitle:tzImagePickerVc.doneBtnTitleStr forState:UIControlStateDisabled];
  208. [_doneButton setTitleColor:tzImagePickerVc.oKButtonTitleColorNormal forState:UIControlStateNormal];
  209. [_doneButton setTitleColor:tzImagePickerVc.oKButtonTitleColorDisabled forState:UIControlStateDisabled];
  210. _doneButton.enabled = tzImagePickerVc.selectedModels.count || tzImagePickerVc.alwaysEnableDoneBtn;
  211. _numberImageView = [[UIImageView alloc] initWithImage:[UIImage imageNamedFromMyBundle:tzImagePickerVc.photoNumberIconImageName]];
  212. _numberImageView.frame = CGRectMake(self.view.tz_width - 56 - 28, 10, 30, 30);
  213. _numberImageView.hidden = tzImagePickerVc.selectedModels.count <= 0;
  214. _numberImageView.backgroundColor = [UIColor clearColor];
  215. _numberLabel = [[UILabel alloc] init];
  216. _numberLabel.frame = _numberImageView.frame;
  217. _numberLabel.font = [UIFont systemFontOfSize:15];
  218. _numberLabel.textColor = [UIColor whiteColor];
  219. _numberLabel.textAlignment = NSTextAlignmentCenter;
  220. _numberLabel.text = [NSString stringWithFormat:@"%zd",tzImagePickerVc.selectedModels.count];
  221. _numberLabel.hidden = tzImagePickerVc.selectedModels.count <= 0;
  222. _numberLabel.backgroundColor = [UIColor clearColor];
  223. UIView *divide = [[UIView alloc] init];
  224. CGFloat rgb2 = 222 / 255.0;
  225. divide.backgroundColor = [UIColor colorWithRed:rgb2 green:rgb2 blue:rgb2 alpha:1.0];
  226. divide.frame = CGRectMake(0, 0, self.view.tz_width, 1);
  227. [bottomToolBar addSubview:divide];
  228. [bottomToolBar addSubview:_previewButton];
  229. [bottomToolBar addSubview:_doneButton];
  230. [bottomToolBar addSubview:_numberImageView];
  231. [bottomToolBar addSubview:_numberLabel];
  232. [self.view addSubview:bottomToolBar];
  233. [self.view addSubview:_originalPhotoButton];
  234. [_originalPhotoButton addSubview:_originalPhotoLabel];
  235. }
  236. #pragma mark - Click Event
  237. - (void)previewButtonClick {
  238. TZPhotoPreviewController *photoPreviewVc = [[TZPhotoPreviewController alloc] init];
  239. [self pushPhotoPrevireViewController:photoPreviewVc];
  240. }
  241. - (void)originalPhotoButtonClick {
  242. _originalPhotoButton.selected = !_originalPhotoButton.isSelected;
  243. _isSelectOriginalPhoto = _originalPhotoButton.isSelected;
  244. _originalPhotoLabel.hidden = !_originalPhotoButton.isSelected;
  245. if (_isSelectOriginalPhoto) [self getSelectedPhotoBytes];
  246. }
  247. - (void)doneButtonClick {
  248. TZImagePickerController *tzImagePickerVc = (TZImagePickerController *)self.navigationController;
  249. // 1.6.8 判断是否满足最小必选张数的限制
  250. if (tzImagePickerVc.minImagesCount && tzImagePickerVc.selectedModels.count < tzImagePickerVc.minImagesCount) {
  251. NSString *title = [NSString stringWithFormat:[NSBundle tz_localizedStringForKey:@"Select a minimum of %zd photos"], tzImagePickerVc.minImagesCount];
  252. [tzImagePickerVc showAlertWithTitle:title];
  253. return;
  254. }
  255. [tzImagePickerVc showProgressHUD];
  256. NSMutableArray *photos = [NSMutableArray array];
  257. NSMutableArray *assets = [NSMutableArray array];
  258. NSMutableArray *infoArr = [NSMutableArray array];
  259. for (NSInteger i = 0; i < tzImagePickerVc.selectedModels.count; i++) { [photos addObject:@1];[assets addObject:@1];[infoArr addObject:@1]; }
  260. __block BOOL havenotShowAlert = YES;
  261. [TZImageManager manager].shouldFixOrientation = YES;
  262. for (NSInteger i = 0; i < tzImagePickerVc.selectedModels.count; i++) {
  263. TZAssetModel *model = tzImagePickerVc.selectedModels[i];
  264. [[TZImageManager manager] getPhotoWithAsset:model.asset completion:^(UIImage *photo, NSDictionary *info, BOOL isDegraded) {
  265. if (isDegraded) return;
  266. if (photo) {
  267. photo = [self scaleImage:photo toSize:CGSizeMake(tzImagePickerVc.photoWidth, (int)(tzImagePickerVc.photoWidth * photo.size.height / photo.size.width))];
  268. [photos replaceObjectAtIndex:i withObject:photo];
  269. }
  270. if (info) [infoArr replaceObjectAtIndex:i withObject:info];
  271. [assets replaceObjectAtIndex:i withObject:model.asset];
  272. for (id item in photos) { if ([item isKindOfClass:[NSNumber class]]) return; }
  273. if (havenotShowAlert) {
  274. [self didGetAllPhotos:photos assets:assets infoArr:infoArr];
  275. }
  276. } progressHandler:^(double progress, NSError *error, BOOL *stop, NSDictionary *info) {
  277. // 如果图片正在从iCloud同步中,提醒用户
  278. if (progress < 1 && havenotShowAlert) {
  279. [tzImagePickerVc hideProgressHUD];
  280. [tzImagePickerVc showAlertWithTitle:[NSBundle tz_localizedStringForKey:@"Synchronizing photos from iCloud"]];
  281. havenotShowAlert = NO;
  282. return;
  283. }
  284. } networkAccessAllowed:YES];
  285. }
  286. if (tzImagePickerVc.selectedModels.count <= 0) {
  287. [self didGetAllPhotos:photos assets:assets infoArr:infoArr];
  288. }
  289. }
  290. - (void)didGetAllPhotos:(NSArray *)photos assets:(NSArray *)assets infoArr:(NSArray *)infoArr {
  291. TZImagePickerController *tzImagePickerVc = (TZImagePickerController *)self.navigationController;
  292. [tzImagePickerVc hideProgressHUD];
  293. if (tzImagePickerVc.autoDismiss) {
  294. [self.navigationController dismissViewControllerAnimated:YES completion:^{
  295. [self callDelegateMethodWithPhotos:photos assets:assets infoArr:infoArr];
  296. }];
  297. } else {
  298. [self callDelegateMethodWithPhotos:photos assets:assets infoArr:infoArr];
  299. }
  300. }
  301. - (void)callDelegateMethodWithPhotos:(NSArray *)photos assets:(NSArray *)assets infoArr:(NSArray *)infoArr {
  302. TZImagePickerController *tzImagePickerVc = (TZImagePickerController *)self.navigationController;
  303. if ([tzImagePickerVc.pickerDelegate respondsToSelector:@selector(imagePickerController:didFinishPickingPhotos:sourceAssets:isSelectOriginalPhoto:)]) {
  304. [tzImagePickerVc.pickerDelegate imagePickerController:tzImagePickerVc didFinishPickingPhotos:photos sourceAssets:assets isSelectOriginalPhoto:_isSelectOriginalPhoto];
  305. }
  306. if ([tzImagePickerVc.pickerDelegate respondsToSelector:@selector(imagePickerController:didFinishPickingPhotos:sourceAssets:isSelectOriginalPhoto:infos:)]) {
  307. [tzImagePickerVc.pickerDelegate imagePickerController:tzImagePickerVc didFinishPickingPhotos:photos sourceAssets:assets isSelectOriginalPhoto:_isSelectOriginalPhoto infos:infoArr];
  308. }
  309. if (tzImagePickerVc.didFinishPickingPhotosHandle) {
  310. tzImagePickerVc.didFinishPickingPhotosHandle(photos,assets,_isSelectOriginalPhoto);
  311. }
  312. if (tzImagePickerVc.didFinishPickingPhotosWithInfosHandle) {
  313. tzImagePickerVc.didFinishPickingPhotosWithInfosHandle(photos,assets,_isSelectOriginalPhoto,infoArr);
  314. }
  315. }
  316. #pragma mark - UICollectionViewDataSource && Delegate
  317. - (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
  318. if (_showTakePhotoBtn) {
  319. TZImagePickerController *tzImagePickerVc = (TZImagePickerController *)self.navigationController;
  320. if (tzImagePickerVc.allowPickingImage && tzImagePickerVc.allowTakePicture) {
  321. return _models.count + 1;
  322. }
  323. }
  324. return _models.count;
  325. }
  326. - (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
  327. // the cell lead to take a picture / 去拍照的cell
  328. TZImagePickerController *tzImagePickerVc = (TZImagePickerController *)self.navigationController;
  329. if (((tzImagePickerVc.sortAscendingByModificationDate && indexPath.row >= _models.count) || (!tzImagePickerVc.sortAscendingByModificationDate && indexPath.row == 0)) && _showTakePhotoBtn) {
  330. TZAssetCameraCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"TZAssetCameraCell" forIndexPath:indexPath];
  331. cell.imageView.image = [UIImage imageNamedFromMyBundle:tzImagePickerVc.takePictureImageName];
  332. return cell;
  333. }
  334. // the cell dipaly photo or video / 展示照片或视频的cell
  335. TZAssetCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"TZAssetCell" forIndexPath:indexPath];
  336. cell.photoDefImageName = tzImagePickerVc.photoDefImageName;
  337. cell.photoSelImageName = tzImagePickerVc.photoSelImageName;
  338. TZAssetModel *model;
  339. if (tzImagePickerVc.sortAscendingByModificationDate || !_showTakePhotoBtn) {
  340. model = _models[indexPath.row];
  341. } else {
  342. model = _models[indexPath.row - 1];
  343. }
  344. cell.allowPickingGif = tzImagePickerVc.allowPickingGif;
  345. cell.model = model;
  346. cell.showSelectBtn = tzImagePickerVc.showSelectBtn;
  347. if (!tzImagePickerVc.allowPreview) {
  348. cell.selectPhotoButton.frame = cell.bounds;
  349. }
  350. __weak typeof(cell) weakCell = cell;
  351. __weak typeof(self) weakSelf = self;
  352. __weak typeof(_numberImageView.layer) weakLayer = _numberImageView.layer;
  353. cell.didSelectPhotoBlock = ^(BOOL isSelected) {
  354. TZImagePickerController *tzImagePickerVc = (TZImagePickerController *)weakSelf.navigationController;
  355. // 1. cancel select / 取消选择
  356. if (isSelected) {
  357. weakCell.selectPhotoButton.selected = NO;
  358. model.isSelected = NO;
  359. NSArray *selectedModels = [NSArray arrayWithArray:tzImagePickerVc.selectedModels];
  360. for (TZAssetModel *model_item in selectedModels) {
  361. if ([[[TZImageManager manager] getAssetIdentifier:model.asset] isEqualToString:[[TZImageManager manager] getAssetIdentifier:model_item.asset]]) {
  362. [tzImagePickerVc.selectedModels removeObject:model_item];
  363. break;
  364. }
  365. }
  366. [weakSelf refreshBottomToolBarStatus];
  367. } else {
  368. // 2. select:check if over the maxImagesCount / 选择照片,检查是否超过了最大个数的限制
  369. if (tzImagePickerVc.selectedModels.count < tzImagePickerVc.maxImagesCount) {
  370. weakCell.selectPhotoButton.selected = YES;
  371. model.isSelected = YES;
  372. [tzImagePickerVc.selectedModels addObject:model];
  373. [weakSelf refreshBottomToolBarStatus];
  374. } else {
  375. NSString *title = [NSString stringWithFormat:[NSBundle tz_localizedStringForKey:@"Select a maximum of %zd photos"], tzImagePickerVc.maxImagesCount];
  376. [tzImagePickerVc showAlertWithTitle:title];
  377. }
  378. }
  379. [UIView showOscillatoryAnimationWithLayer:weakLayer type:TZOscillatoryAnimationToSmaller];
  380. };
  381. return cell;
  382. }
  383. - (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
  384. // take a photo / 去拍照
  385. TZImagePickerController *tzImagePickerVc = (TZImagePickerController *)self.navigationController;
  386. if (((tzImagePickerVc.sortAscendingByModificationDate && indexPath.row >= _models.count) || (!tzImagePickerVc.sortAscendingByModificationDate && indexPath.row == 0)) && _showTakePhotoBtn) {
  387. [self takePhoto]; return;
  388. }
  389. // preview phote or video / 预览照片或视频
  390. NSInteger index = indexPath.row;
  391. if (!tzImagePickerVc.sortAscendingByModificationDate && _showTakePhotoBtn) {
  392. index = indexPath.row - 1;
  393. }
  394. TZAssetModel *model = _models[index];
  395. if (model.type == TZAssetModelMediaTypeVideo) {
  396. if (tzImagePickerVc.selectedModels.count > 0) {
  397. TZImagePickerController *imagePickerVc = (TZImagePickerController *)self.navigationController;
  398. [imagePickerVc showAlertWithTitle:[NSBundle tz_localizedStringForKey:@"Can not choose both video and photo"]];
  399. } else {
  400. TZVideoPlayerController *videoPlayerVc = [[TZVideoPlayerController alloc] init];
  401. videoPlayerVc.model = model;
  402. [self.navigationController pushViewController:videoPlayerVc animated:YES];
  403. }
  404. } else if (model.type == TZAssetModelMediaTypePhotoGif && tzImagePickerVc.allowPickingGif) {
  405. if (tzImagePickerVc.selectedModels.count > 0) {
  406. TZImagePickerController *imagePickerVc = (TZImagePickerController *)self.navigationController;
  407. [imagePickerVc showAlertWithTitle:[NSBundle tz_localizedStringForKey:@"Can not choose both photo and GIF"]];
  408. } else {
  409. TZGifPhotoPreviewController *gifPreviewVc = [[TZGifPhotoPreviewController alloc] init];
  410. gifPreviewVc.model = model;
  411. [self.navigationController pushViewController:gifPreviewVc animated:YES];
  412. }
  413. } else {
  414. TZPhotoPreviewController *photoPreviewVc = [[TZPhotoPreviewController alloc] init];
  415. photoPreviewVc.currentIndex = index;
  416. photoPreviewVc.models = _models;
  417. [self pushPhotoPrevireViewController:photoPreviewVc];
  418. }
  419. }
  420. #pragma mark - UIScrollViewDelegate
  421. - (void)scrollViewDidScroll:(UIScrollView *)scrollView {
  422. if (iOS8Later) {
  423. // [self updateCachedAssets];
  424. }
  425. }
  426. #pragma mark - Private Method
  427. - (void)takePhoto {
  428. AVAuthorizationStatus authStatus = [AVCaptureDevice authorizationStatusForMediaType:AVMediaTypeVideo];
  429. if ((authStatus == AVAuthorizationStatusRestricted || authStatus ==AVAuthorizationStatusDenied) && iOS7Later) {
  430. // 无权限 做一个友好的提示
  431. NSString *appName = [[NSBundle mainBundle].infoDictionary valueForKey:@"CFBundleDisplayName"];
  432. if (!appName) appName = [[NSBundle mainBundle].infoDictionary valueForKey:@"CFBundleName"];
  433. NSString *message = [NSString stringWithFormat:[NSBundle tz_localizedStringForKey:@"Please allow %@ to access your camera in \"Settings -> Privacy -> Camera\""],appName];
  434. 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];
  435. [alert show];
  436. } else { // 调用相机
  437. UIImagePickerControllerSourceType sourceType = UIImagePickerControllerSourceTypeCamera;
  438. if ([UIImagePickerController isSourceTypeAvailable: UIImagePickerControllerSourceTypeCamera]) {
  439. self.imagePickerVc.sourceType = sourceType;
  440. if(iOS8Later) {
  441. _imagePickerVc.modalPresentationStyle = UIModalPresentationOverCurrentContext;
  442. }
  443. [self presentViewController:_imagePickerVc animated:YES completion:nil];
  444. } else {
  445. NSLog(ASLocalizedString(@"模拟器中无法打开照相机,请在真机中使用"));
  446. }
  447. }
  448. }
  449. - (void)refreshBottomToolBarStatus {
  450. TZImagePickerController *tzImagePickerVc = (TZImagePickerController *)self.navigationController;
  451. _previewButton.enabled = tzImagePickerVc.selectedModels.count > 0;
  452. _doneButton.enabled = tzImagePickerVc.selectedModels.count > 0 || tzImagePickerVc.alwaysEnableDoneBtn;
  453. _numberImageView.hidden = tzImagePickerVc.selectedModels.count <= 0;
  454. _numberLabel.hidden = tzImagePickerVc.selectedModels.count <= 0;
  455. _numberLabel.text = [NSString stringWithFormat:@"%zd",tzImagePickerVc.selectedModels.count];
  456. _originalPhotoButton.enabled = tzImagePickerVc.selectedModels.count > 0;
  457. _originalPhotoButton.selected = (_isSelectOriginalPhoto && _originalPhotoButton.enabled);
  458. _originalPhotoLabel.hidden = (!_originalPhotoButton.isSelected);
  459. if (_isSelectOriginalPhoto) [self getSelectedPhotoBytes];
  460. }
  461. - (void)pushPhotoPrevireViewController:(TZPhotoPreviewController *)photoPreviewVc {
  462. __weak typeof(self) weakSelf = self;
  463. photoPreviewVc.isSelectOriginalPhoto = _isSelectOriginalPhoto;
  464. [photoPreviewVc setBackButtonClickBlock:^(BOOL isSelectOriginalPhoto) {
  465. weakSelf.isSelectOriginalPhoto = isSelectOriginalPhoto;
  466. [weakSelf.collectionView reloadData];
  467. [weakSelf refreshBottomToolBarStatus];
  468. }];
  469. [photoPreviewVc setDoneButtonClickBlock:^(BOOL isSelectOriginalPhoto) {
  470. weakSelf.isSelectOriginalPhoto = isSelectOriginalPhoto;
  471. [weakSelf doneButtonClick];
  472. }];
  473. [photoPreviewVc setDoneButtonClickBlockCropMode:^(UIImage *cropedImage, id asset) {
  474. [weakSelf didGetAllPhotos:@[cropedImage] assets:@[asset] infoArr:nil];
  475. }];
  476. [self.navigationController pushViewController:photoPreviewVc animated:YES];
  477. }
  478. - (void)getSelectedPhotoBytes {
  479. TZImagePickerController *imagePickerVc = (TZImagePickerController *)self.navigationController;
  480. [[TZImageManager manager] getPhotosBytesWithArray:imagePickerVc.selectedModels completion:^(NSString *totalBytes) {
  481. _originalPhotoLabel.text = [NSString stringWithFormat:@"(%@)",totalBytes];
  482. }];
  483. }
  484. /// Scale image / 缩放图片
  485. - (UIImage *)scaleImage:(UIImage *)image toSize:(CGSize)size {
  486. if (image.size.width < size.width) {
  487. return image;
  488. }
  489. UIGraphicsBeginImageContext(size);
  490. [image drawInRect:CGRectMake(0, 0, size.width, size.height)];
  491. UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
  492. UIGraphicsEndImageContext();
  493. return newImage;
  494. }
  495. - (void)scrollCollectionViewToBottom {
  496. TZImagePickerController *tzImagePickerVc = (TZImagePickerController *)self.navigationController;
  497. if (_shouldScrollToBottom && _models.count > 0 && tzImagePickerVc.sortAscendingByModificationDate) {
  498. NSInteger item = _models.count - 1;
  499. if (_showTakePhotoBtn) {
  500. TZImagePickerController *tzImagePickerVc = (TZImagePickerController *)self.navigationController;
  501. if (tzImagePickerVc.allowPickingImage && tzImagePickerVc.allowTakePicture) {
  502. item += 1;
  503. }
  504. }
  505. [_collectionView scrollToItemAtIndexPath:[NSIndexPath indexPathForItem:item inSection:0] atScrollPosition:UICollectionViewScrollPositionBottom animated:NO];
  506. _shouldScrollToBottom = NO;
  507. }
  508. }
  509. - (void)checkSelectedModels {
  510. for (TZAssetModel *model in _models) {
  511. model.isSelected = NO;
  512. NSMutableArray *selectedAssets = [NSMutableArray array];
  513. TZImagePickerController *tzImagePickerVc = (TZImagePickerController *)self.navigationController;
  514. for (TZAssetModel *model in tzImagePickerVc.selectedModels) {
  515. [selectedAssets addObject:model.asset];
  516. }
  517. if ([[TZImageManager manager] isAssetsArray:selectedAssets containAsset:model.asset]) {
  518. model.isSelected = YES;
  519. }
  520. }
  521. }
  522. #pragma mark - UIAlertViewDelegate
  523. - (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex {
  524. if (buttonIndex == 1) { // 去设置界面,开启相机访问权限
  525. [[UIApplication sharedApplication] openURL:[NSURL URLWithString:UIApplicationOpenSettingsURLString]];
  526. }
  527. }
  528. #pragma mark - UIImagePickerControllerDelegate
  529. - (void)imagePickerController:(UIImagePickerController*)picker didFinishPickingMediaWithInfo:(NSDictionary *)info {
  530. [picker dismissViewControllerAnimated:YES completion:nil];
  531. NSString *type = [info objectForKey:UIImagePickerControllerMediaType];
  532. if ([type isEqualToString:@"public.image"]) {
  533. TZImagePickerController *imagePickerVc = (TZImagePickerController *)self.navigationController;
  534. [imagePickerVc showProgressHUD];
  535. UIImage *image = [info objectForKey:UIImagePickerControllerOriginalImage];
  536. if (image) {
  537. [[TZImageManager manager] savePhotoWithImage:image completion:^(NSError *error){
  538. if (!error) {
  539. [self reloadPhotoArray];
  540. }
  541. }];
  542. }
  543. }
  544. }
  545. - (void)reloadPhotoArray {
  546. TZImagePickerController *tzImagePickerVc = (TZImagePickerController *)self.navigationController;
  547. [[TZImageManager manager] getCameraRollAlbum:tzImagePickerVc.allowPickingVideo allowPickingImage:tzImagePickerVc.allowPickingImage completion:^(TZAlbumModel *model) {
  548. _model = model;
  549. [[TZImageManager manager] getAssetsFromFetchResult:_model.result allowPickingVideo:tzImagePickerVc.allowPickingVideo allowPickingImage:tzImagePickerVc.allowPickingImage completion:^(NSArray<TZAssetModel *> *models) {
  550. [tzImagePickerVc hideProgressHUD];
  551. TZAssetModel *assetModel;
  552. if (tzImagePickerVc.sortAscendingByModificationDate) {
  553. assetModel = [models lastObject];
  554. [_models addObject:assetModel];
  555. } else {
  556. assetModel = [models firstObject];
  557. [_models insertObject:assetModel atIndex:0];
  558. }
  559. if (tzImagePickerVc.maxImagesCount <= 1) {
  560. if (tzImagePickerVc.allowCrop) {
  561. TZPhotoPreviewController *photoPreviewVc = [[TZPhotoPreviewController alloc] init];
  562. photoPreviewVc.currentIndex = _models.count - 1;
  563. photoPreviewVc.models = _models;
  564. [self pushPhotoPrevireViewController:photoPreviewVc];
  565. } else {
  566. [tzImagePickerVc.selectedModels addObject:assetModel];
  567. [self doneButtonClick];
  568. }
  569. return;
  570. }
  571. if (tzImagePickerVc.selectedModels.count < tzImagePickerVc.maxImagesCount) {
  572. assetModel.isSelected = YES;
  573. [tzImagePickerVc.selectedModels addObject:assetModel];
  574. [self refreshBottomToolBarStatus];
  575. }
  576. [_collectionView reloadData];
  577. _shouldScrollToBottom = YES;
  578. [self scrollCollectionViewToBottom];
  579. }];
  580. }];
  581. }
  582. - (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker {
  583. [picker dismissViewControllerAnimated:YES completion:nil];
  584. }
  585. - (void)dealloc {
  586. //NSLog(@"TZPhotoPickerController dealloc");
  587. }
  588. #pragma mark - Asset Caching
  589. - (void)resetCachedAssets {
  590. [[TZImageManager manager].cachingImageManager stopCachingImagesForAllAssets];
  591. self.previousPreheatRect = CGRectZero;
  592. }
  593. - (void)updateCachedAssets {
  594. BOOL isViewVisible = [self isViewLoaded] && [[self view] window] != nil;
  595. if (!isViewVisible) { return; }
  596. // The preheat window is twice the height of the visible rect.
  597. CGRect preheatRect = _collectionView.bounds;
  598. preheatRect = CGRectInset(preheatRect, 0.0f, -0.5f * CGRectGetHeight(preheatRect));
  599. /*
  600. Check if the collection view is showing an area that is significantly
  601. different to the last preheated area.
  602. */
  603. CGFloat delta = ABS(CGRectGetMidY(preheatRect) - CGRectGetMidY(self.previousPreheatRect));
  604. if (delta > CGRectGetHeight(_collectionView.bounds) / 3.0f) {
  605. // Compute the assets to start caching and to stop caching.
  606. NSMutableArray *addedIndexPaths = [NSMutableArray array];
  607. NSMutableArray *removedIndexPaths = [NSMutableArray array];
  608. [self computeDifferenceBetweenRect:self.previousPreheatRect andRect:preheatRect removedHandler:^(CGRect removedRect) {
  609. NSArray *indexPaths = [self aapl_indexPathsForElementsInRect:removedRect];
  610. [removedIndexPaths addObjectsFromArray:indexPaths];
  611. } addedHandler:^(CGRect addedRect) {
  612. NSArray *indexPaths = [self aapl_indexPathsForElementsInRect:addedRect];
  613. [addedIndexPaths addObjectsFromArray:indexPaths];
  614. }];
  615. NSArray *assetsToStartCaching = [self assetsAtIndexPaths:addedIndexPaths];
  616. NSArray *assetsToStopCaching = [self assetsAtIndexPaths:removedIndexPaths];
  617. // Update the assets the PHCachingImageManager is caching.
  618. [[TZImageManager manager].cachingImageManager startCachingImagesForAssets:assetsToStartCaching
  619. targetSize:AssetGridThumbnailSize
  620. contentMode:PHImageContentModeAspectFill
  621. options:nil];
  622. [[TZImageManager manager].cachingImageManager stopCachingImagesForAssets:assetsToStopCaching
  623. targetSize:AssetGridThumbnailSize
  624. contentMode:PHImageContentModeAspectFill
  625. options:nil];
  626. // Store the preheat rect to compare against in the future.
  627. self.previousPreheatRect = preheatRect;
  628. }
  629. }
  630. - (void)computeDifferenceBetweenRect:(CGRect)oldRect andRect:(CGRect)newRect removedHandler:(void (^)(CGRect removedRect))removedHandler addedHandler:(void (^)(CGRect addedRect))addedHandler {
  631. if (CGRectIntersectsRect(newRect, oldRect)) {
  632. CGFloat oldMaxY = CGRectGetMaxY(oldRect);
  633. CGFloat oldMinY = CGRectGetMinY(oldRect);
  634. CGFloat newMaxY = CGRectGetMaxY(newRect);
  635. CGFloat newMinY = CGRectGetMinY(newRect);
  636. if (newMaxY > oldMaxY) {
  637. CGRect rectToAdd = CGRectMake(newRect.origin.x, oldMaxY, newRect.size.width, (newMaxY - oldMaxY));
  638. addedHandler(rectToAdd);
  639. }
  640. if (oldMinY > newMinY) {
  641. CGRect rectToAdd = CGRectMake(newRect.origin.x, newMinY, newRect.size.width, (oldMinY - newMinY));
  642. addedHandler(rectToAdd);
  643. }
  644. if (newMaxY < oldMaxY) {
  645. CGRect rectToRemove = CGRectMake(newRect.origin.x, newMaxY, newRect.size.width, (oldMaxY - newMaxY));
  646. removedHandler(rectToRemove);
  647. }
  648. if (oldMinY < newMinY) {
  649. CGRect rectToRemove = CGRectMake(newRect.origin.x, oldMinY, newRect.size.width, (newMinY - oldMinY));
  650. removedHandler(rectToRemove);
  651. }
  652. } else {
  653. addedHandler(newRect);
  654. removedHandler(oldRect);
  655. }
  656. }
  657. - (NSArray *)assetsAtIndexPaths:(NSArray *)indexPaths {
  658. if (indexPaths.count == 0) { return nil; }
  659. NSMutableArray *assets = [NSMutableArray arrayWithCapacity:indexPaths.count];
  660. for (NSIndexPath *indexPath in indexPaths) {
  661. if (indexPath.item < _models.count) {
  662. TZAssetModel *model = _models[indexPath.item];
  663. [assets addObject:model.asset];
  664. }
  665. }
  666. return assets;
  667. }
  668. - (NSArray *)aapl_indexPathsForElementsInRect:(CGRect)rect {
  669. NSArray *allLayoutAttributes = [_collectionView.collectionViewLayout layoutAttributesForElementsInRect:rect];
  670. if (allLayoutAttributes.count == 0) { return nil; }
  671. NSMutableArray *indexPaths = [NSMutableArray arrayWithCapacity:allLayoutAttributes.count];
  672. for (UICollectionViewLayoutAttributes *layoutAttributes in allLayoutAttributes) {
  673. NSIndexPath *indexPath = layoutAttributes.indexPath;
  674. [indexPaths addObject:indexPath];
  675. }
  676. return indexPaths;
  677. }
  678. #pragma clang diagnostic pop
  679. @end
  680. @implementation TZCollectionView
  681. - (BOOL)touchesShouldCancelInContentView:(UIView *)view {
  682. if ( [view isKindOfClass:[UIControl class]]) {
  683. return YES;
  684. }
  685. return [super touchesShouldCancelInContentView:view];
  686. }
  687. @end