UzysAssetsPickerController.m 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824
  1. //
  2. // UzysAssetsPickerController.m
  3. // UzysAssetsPickerController
  4. //
  5. // Created by Uzysjung on 2014. 2. 12..
  6. // Copyright (c) 2014년 Uzys. All rights reserved.
  7. //
  8. // 版权属于原作者
  9. // http://code4app.com(cn) http://code4app.net(en)
  10. // 来源于最专业的源码分享网站: Code4App
  11. #import "UzysAssetsPickerController.h"
  12. #import "UzysAssetsViewCell.h"
  13. #import "UzysWrapperPickerController.h"
  14. #import "UzysGroupPickerView.h"
  15. #import "UzysGroupPickerViewController.h"
  16. @interface UzysAssetsPickerController ()<UICollectionViewDataSource,UICollectionViewDelegate,UIImagePickerControllerDelegate,UINavigationControllerDelegate>
  17. //View
  18. @property (weak, nonatomic) IBOutlet UIButton *btnTitle;
  19. @property (weak, nonatomic) IBOutlet UIButton *btnDone;
  20. @property (weak, nonatomic) IBOutlet UIView *navigationTop;
  21. @property (weak, nonatomic) IBOutlet UIView *bottomView;
  22. @property (weak, nonatomic) IBOutlet UISegmentedControl *segmentedControl;
  23. @property (weak, nonatomic) IBOutlet UILabel *labelSelectedMedia;
  24. @property (weak, nonatomic) IBOutlet UIButton *btnCamera;
  25. @property (nonatomic, strong) UIView *noAssetView;
  26. @property (nonatomic, strong) UICollectionView *collectionView;
  27. @property (nonatomic, strong) UzysWrapperPickerController *picker;
  28. @property (nonatomic, strong) UzysGroupPickerView *groupPicker;
  29. @property (nonatomic, strong) ALAssetsGroup *assetsGroup;
  30. @property (nonatomic, strong) NSMutableArray *groups;
  31. @property (nonatomic, strong) ALAssetsLibrary *assetsLibrary;
  32. @property (nonatomic, strong) NSMutableArray *assets;
  33. @property (nonatomic, assign) NSInteger numberOfPhotos;
  34. @property (nonatomic, assign) NSInteger numberOfVideos;
  35. @property (nonatomic, assign) NSInteger maximumNumberOfSelection;
  36. - (IBAction)btnAction:(id)sender;
  37. - (IBAction)indexDidChangeForSegmentedControl:(id)sender;
  38. @end
  39. @implementation UzysAssetsPickerController
  40. #pragma mark - ALAssetsLibrary
  41. + (ALAssetsLibrary *)defaultAssetsLibrary
  42. {
  43. static dispatch_once_t pred = 0;
  44. static ALAssetsLibrary *library = nil;
  45. dispatch_once(&pred,^
  46. {
  47. library = [[ALAssetsLibrary alloc] init];
  48. });
  49. return library;
  50. }
  51. - (id)init
  52. {
  53. self = [super initWithNibName:@"UzysAssetsPickerController" bundle:nil];
  54. if(self)
  55. {
  56. [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(assetsLibraryUpdated:) name:ALAssetsLibraryChangedNotification object:nil];
  57. }
  58. return self;
  59. }
  60. - (void)dealloc
  61. {
  62. [[NSNotificationCenter defaultCenter] removeObserver:self name:ALAssetsLibraryChangedNotification object:nil];
  63. self.assetsLibrary = nil;
  64. self.assetsGroup = nil;
  65. self.assets = nil;
  66. }
  67. - (void)didReceiveMemoryWarning
  68. {
  69. [super didReceiveMemoryWarning];
  70. // Dispose of any resources that can be recreated.
  71. }
  72. - (void)viewDidLoad
  73. {
  74. [super viewDidLoad];
  75. // Do any additional setup after loading the view from its nib.
  76. [self initVariable];
  77. [self initImagePicker];
  78. [self setupOneMediaTypeSelection];
  79. __weak typeof(self) weakSelf = self;
  80. [self setupGroup:^{
  81. [weakSelf.groupPicker.tableView selectRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:0] animated:NO scrollPosition:UITableViewScrollPositionNone];
  82. } withSetupAsset:YES];
  83. [self setupLayout];
  84. [self setupCollectionView];
  85. [self setupGroupPickerview];
  86. [self initNoAssetView];
  87. }
  88. - (void)initVariable
  89. {
  90. self.assetsFilter = [ALAssetsFilter allPhotos];
  91. self.maximumNumberOfSelection = self.maximumNumberOfSelectionPhoto;
  92. self.view.clipsToBounds = YES;
  93. }
  94. - (void)initImagePicker
  95. {
  96. UzysWrapperPickerController *picker = [[UzysWrapperPickerController alloc] init];
  97. // picker.modalPresentationStyle = UIModalPresentationCurrentContext;
  98. picker.delegate = self;
  99. picker.allowsEditing = NO;
  100. picker.videoQuality = UIImagePickerControllerQualityTypeHigh;
  101. if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera])
  102. {
  103. picker.sourceType = UIImagePickerControllerSourceTypeCamera;
  104. picker.mediaTypes =
  105. [UIImagePickerController availableMediaTypesForSourceType:
  106. UIImagePickerControllerSourceTypeCamera];
  107. }
  108. self.picker = picker;
  109. }
  110. - (void)initNoAssetView
  111. {
  112. UIView *noAssetsView = [[UIView alloc] initWithFrame:self.collectionView.bounds];
  113. CGRect rect = CGRectInset(self.collectionView.bounds, 10, 10);
  114. UILabel *title = [[UILabel alloc] initWithFrame:rect];
  115. UILabel *message = [[UILabel alloc] initWithFrame:rect];
  116. title.text = NSLocalizedString(@"No Photos or Videos", nil);
  117. title.font = [UIFont systemFontOfSize:19.0];
  118. title.textColor = [UIColor colorWithRed:153.0/255.0 green:153.0/255.0 blue:153.0/255.0 alpha:1];
  119. title.textAlignment = NSTextAlignmentCenter;
  120. title.numberOfLines = 5;
  121. title.tag = kTagNoAssetViewTitleLabel;
  122. message.text = NSLocalizedStringFromTable(@"You can sync photos and videos onto your iPhone using iTunes.", @"UzysAssetsPickerController",nil);
  123. message.font = [UIFont systemFontOfSize:15.0];
  124. message.textColor = [UIColor colorWithRed:153.0/255.0 green:153.0/255.0 blue:153.0/255.0 alpha:1];
  125. message.textAlignment = NSTextAlignmentCenter;
  126. message.numberOfLines = 5;
  127. message.tag = kTagNoAssetViewMsgLabel;
  128. UIImageView *titleImage = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"UzysAssetPickerController.bundle/uzysAP_ico_no_image"]];
  129. titleImage.contentMode = UIViewContentModeCenter;
  130. titleImage.tag = kTagNoAssetViewImageView;
  131. [title sizeToFit];
  132. [message sizeToFit];
  133. title.center = CGPointMake(noAssetsView.center.x, noAssetsView.center.y - 10 - title.frame.size.height / 2 + 40);
  134. message.center = CGPointMake(noAssetsView.center.x, noAssetsView.center.y + 10 + message.frame.size.height / 2 + 20);
  135. titleImage.center = CGPointMake(noAssetsView.center.x, noAssetsView.center.y - 10 - titleImage.frame.size.height /2);
  136. [noAssetsView addSubview:title];
  137. [noAssetsView addSubview:message];
  138. [noAssetsView addSubview:titleImage];
  139. [self.collectionView addSubview:noAssetsView];
  140. self.noAssetView = noAssetsView;
  141. self.noAssetView.hidden = YES;
  142. }
  143. - (void)setupLayout
  144. {
  145. self.btnDone.layer.cornerRadius = 15;
  146. self.btnDone.clipsToBounds = YES;
  147. UIView *lineView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, self.bottomView.bounds.size.width, 0.5)];
  148. lineView.backgroundColor = [UIColor colorWithWhite:0 alpha:0.15f];
  149. [self.bottomView addSubview:lineView];
  150. }
  151. - (void)setupGroupPickerview
  152. {
  153. __weak typeof(self) weakSelf = self;
  154. self.groupPicker = [[UzysGroupPickerView alloc] initWithGroups:self.groups];
  155. self.groupPicker.blockTouchCell = ^(NSInteger row){
  156. [weakSelf changeGroup:row filter:weakSelf.assetsFilter];
  157. };
  158. [self.view insertSubview:self.groupPicker aboveSubview:self.bottomView];
  159. [self.view bringSubviewToFront:self.navigationTop];
  160. [self menuArrowRotate];
  161. }
  162. - (void)setupOneMediaTypeSelection
  163. {
  164. if(_maximumNumberOfSelectionMedia > 0)
  165. {
  166. self.assetsFilter = [ALAssetsFilter allAssets];
  167. self.maximumNumberOfSelection = self.maximumNumberOfSelectionMedia;
  168. self.segmentedControl.hidden = YES;
  169. self.labelSelectedMedia.hidden = NO;
  170. if(_maximumNumberOfSelection >1)
  171. self.labelSelectedMedia.text = @"Choose media";
  172. else
  173. self.labelSelectedMedia.text = @"Choose media";
  174. }
  175. else
  176. {
  177. if(_maximumNumberOfSelectionPhoto ==0)
  178. {
  179. self.assetsFilter = [ALAssetsFilter allVideos];
  180. self.maximumNumberOfSelection = self.maximumNumberOfSelectionVideo;
  181. self.segmentedControl.hidden = YES;
  182. self.labelSelectedMedia.hidden = NO;
  183. if(_maximumNumberOfSelection >1)
  184. self.labelSelectedMedia.text = @"Choose videos";
  185. else
  186. self.labelSelectedMedia.text = @"Choose a video";
  187. }
  188. else if(_maximumNumberOfSelectionVideo ==0)
  189. {
  190. self.assetsFilter = [ALAssetsFilter allPhotos];
  191. self.segmentedControl.selectedSegmentIndex = 0;
  192. self.maximumNumberOfSelection = self.maximumNumberOfSelectionPhoto;
  193. self.segmentedControl.hidden = YES;
  194. self.labelSelectedMedia.hidden = NO;
  195. //去掉不显示英文
  196. if(_maximumNumberOfSelection >1)
  197. self.labelSelectedMedia.text = @"";
  198. else
  199. self.labelSelectedMedia.text = @"";
  200. }
  201. else
  202. {
  203. self.segmentedControl.hidden = NO;
  204. self.labelSelectedMedia.hidden = YES;
  205. }
  206. }
  207. }
  208. - (void)setupCollectionView
  209. {
  210. UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init];
  211. layout.itemSize = kThumbnailSize;
  212. layout.sectionInset = UIEdgeInsetsMake(1.0, 0, 0, 0);
  213. layout.minimumInteritemSpacing = 1.0;
  214. layout.minimumLineSpacing = 1.0;
  215. self.collectionView = [[UICollectionView alloc] initWithFrame:CGRectMake(0, 64, kSize.width, kSize.height - 64 -48) collectionViewLayout:layout];
  216. self.collectionView.allowsMultipleSelection = YES;
  217. [self.collectionView registerClass:[UzysAssetsViewCell class]
  218. forCellWithReuseIdentifier:kAssetsViewCellIdentifier];
  219. self.collectionView.delegate = self;
  220. self.collectionView.dataSource = self;
  221. self.collectionView.backgroundColor = [UIColor whiteColor];
  222. self.collectionView.bounces = YES;
  223. self.collectionView.alwaysBounceVertical = YES;
  224. [self.view insertSubview:self.collectionView atIndex:0];
  225. }
  226. - (void)changeGroup:(NSInteger)item filter:(ALAssetsFilter *)filter
  227. {
  228. self.assetsFilter = filter;
  229. self.assetsGroup = self.groups[item];
  230. [self setupAssets:nil];
  231. [self.groupPicker.tableView selectRowAtIndexPath:[NSIndexPath indexPathForRow:item inSection:0] animated:NO scrollPosition:UITableViewScrollPositionNone];
  232. [self.groupPicker dismiss:YES];
  233. [self menuArrowRotate];
  234. }
  235. - (void)changeAssetType:(BOOL)isPhoto endBlock:(voidBlock)endBlock
  236. {
  237. if(isPhoto)
  238. {
  239. self.maximumNumberOfSelection = self.maximumNumberOfSelectionPhoto;
  240. self.assetsFilter = [ALAssetsFilter allPhotos];
  241. [self setupAssets:endBlock];
  242. }
  243. else
  244. {
  245. self.maximumNumberOfSelection = self.maximumNumberOfSelectionVideo;
  246. self.assetsFilter = [ALAssetsFilter allVideos];
  247. [self setupAssets:endBlock];
  248. }
  249. }
  250. - (void)setupGroup:(voidBlock)endblock withSetupAsset:(BOOL)doSetupAsset
  251. {
  252. if (!self.assetsLibrary)
  253. {
  254. self.assetsLibrary = [self.class defaultAssetsLibrary];
  255. }
  256. if (!self.groups)
  257. self.groups = [[NSMutableArray alloc] init];
  258. else
  259. [self.groups removeAllObjects];
  260. __weak typeof(self) weakSelf = self;
  261. ALAssetsFilter *assetsFilter = [ALAssetsFilter allAssets]; // number of Asset 메쏘드 호출 시에 적용.
  262. ALAssetsLibraryGroupsEnumerationResultsBlock resultsBlock = ^(ALAssetsGroup *group, BOOL *stop) {
  263. if (group)
  264. {
  265. [group setAssetsFilter:assetsFilter];
  266. NSInteger groupType = [[group valueForProperty:ALAssetsGroupPropertyType] integerValue];
  267. if(groupType == ALAssetsGroupSavedPhotos)
  268. {
  269. [weakSelf.groups insertObject:group atIndex:0];
  270. if(doSetupAsset)
  271. {
  272. weakSelf.assetsGroup = group;
  273. [weakSelf setupAssets:nil];
  274. }
  275. }
  276. else
  277. {
  278. if (group.numberOfAssets > 0)
  279. [weakSelf.groups addObject:group];
  280. }
  281. }
  282. else
  283. {
  284. dispatch_async(dispatch_get_main_queue(), ^{
  285. [weakSelf.groupPicker reloadData];
  286. if(endblock)
  287. endblock();
  288. });
  289. }
  290. };
  291. ALAssetsLibraryAccessFailureBlock failureBlock = ^(NSError *error) {
  292. //접근이 허락 안되었을 경우
  293. [self showNotAllowed];
  294. self.segmentedControl.enabled = NO;
  295. self.btnDone.enabled = NO;
  296. self.btnCamera.enabled = NO;
  297. [self.btnTitle setTitle:NSLocalizedStringFromTable(@"Not Allowed", @"UzysAssetsPickerController",nil) forState:UIControlStateNormal];
  298. [self.btnTitle setImage:nil forState:UIControlStateNormal];
  299. };
  300. [self.assetsLibrary enumerateGroupsWithTypes:ALAssetsGroupAll
  301. usingBlock:resultsBlock
  302. failureBlock:failureBlock];
  303. }
  304. - (void)setupAssets:(voidBlock)successBlock
  305. {
  306. self.title = [self.assetsGroup valueForProperty:ALAssetsGroupPropertyName];
  307. if (!self.assets)
  308. self.assets = [[NSMutableArray alloc] init];
  309. else
  310. [self.assets removeAllObjects];
  311. if(!self.assetsGroup)
  312. {
  313. self.assetsGroup = self.groups[0];
  314. }
  315. [self.assetsGroup setAssetsFilter:self.assetsFilter];
  316. NSInteger assetCount = [self.assetsGroup numberOfAssets];
  317. ALAssetsGroupEnumerationResultsBlock resultsBlock = ^(ALAsset *asset, NSUInteger index, BOOL *stop) {
  318. if (asset)
  319. {
  320. [self.assets addObject:asset];
  321. NSString *type = [asset valueForProperty:ALAssetPropertyType];
  322. if ([type isEqual:ALAssetTypePhoto])
  323. self.numberOfPhotos ++;
  324. if ([type isEqual:ALAssetTypeVideo])
  325. self.numberOfVideos ++;
  326. }
  327. else if (self.assets.count >= assetCount)
  328. {
  329. dispatch_async(dispatch_get_main_queue(), ^{
  330. [self reloadData];
  331. if(successBlock)
  332. successBlock();
  333. });
  334. }
  335. };
  336. [self.assetsGroup enumerateAssetsWithOptions:NSEnumerationReverse usingBlock:resultsBlock];
  337. }
  338. - (void)reloadData
  339. {
  340. [self.collectionView reloadData];
  341. [self.btnDone setTitle:[NSString stringWithFormat:@"%lu",(unsigned long)self.collectionView.indexPathsForSelectedItems
  342. .count] forState:UIControlStateNormal];
  343. [self showNoAssetsIfNeeded];
  344. }
  345. - (void)setAssetsCountWithSelectedIndexPaths:(NSArray *)indexPaths
  346. {
  347. [self.btnDone setTitle:[NSString stringWithFormat:@"%lu",(unsigned long)indexPaths.count] forState:UIControlStateNormal];
  348. }
  349. - (void)showNotAllowed
  350. {
  351. self.title = nil;
  352. UIView *lockedView = [[UIView alloc] initWithFrame:self.collectionView.bounds];
  353. UIImageView *locked = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"UzysAssetPickerController.bundle/uzysAP_ico_no_access"]];
  354. locked.contentMode = UIViewContentModeCenter;
  355. CGRect rect = CGRectInset(self.collectionView.bounds, 8, 8);
  356. UILabel *title = [[UILabel alloc] initWithFrame:rect];
  357. UILabel *message = [[UILabel alloc] initWithFrame:rect];
  358. title.text = NSLocalizedStringFromTable(@"This app does not have access to your photos or videos.", @"UzysAssetsPickerController",nil);
  359. title.font = [UIFont boldSystemFontOfSize:17.0];
  360. title.textColor = [UIColor colorWithRed:129.0/255.0 green:136.0/255.0 blue:148.0/255.0 alpha:1];
  361. title.textAlignment = NSTextAlignmentCenter;
  362. title.numberOfLines = 5;
  363. message.text = NSLocalizedStringFromTable(@"You can enable access in Privacy Settings.", @"UzysAssetsPickerController",nil);
  364. message.font = [UIFont systemFontOfSize:14.0];
  365. message.textColor = [UIColor colorWithRed:129.0/255.0 green:136.0/255.0 blue:148.0/255.0 alpha:1];
  366. message.textAlignment = NSTextAlignmentCenter;
  367. message.numberOfLines = 5;
  368. [title sizeToFit];
  369. [message sizeToFit];
  370. locked.center = CGPointMake(lockedView.center.x, lockedView.center.y - locked.bounds.size.height /2 - 20);
  371. title.center = locked.center;
  372. message.center = locked.center;
  373. rect = title.frame;
  374. rect.origin.y = locked.frame.origin.y + locked.frame.size.height + 10;
  375. title.frame = rect;
  376. rect = message.frame;
  377. rect.origin.y = title.frame.origin.y + title.frame.size.height + 5;
  378. message.frame = rect;
  379. [lockedView addSubview:locked];
  380. [lockedView addSubview:title];
  381. [lockedView addSubview:message];
  382. [self.collectionView addSubview:lockedView];
  383. }
  384. - (void)showNoAssetsIfNeeded
  385. {
  386. __weak typeof(self) weakSelf = self;
  387. voidBlock setNoImage = ^{
  388. UIImageView *imgView = (UIImageView *)[weakSelf.noAssetView viewWithTag:kTagNoAssetViewImageView];
  389. imgView.contentMode = UIViewContentModeCenter;
  390. imgView.image = [UIImage imageNamed:@"UzysAssetPickerController.bundle/uzysAP_ico_no_image"];
  391. UILabel *title = (UILabel *)[weakSelf.noAssetView viewWithTag:kTagNoAssetViewTitleLabel];
  392. title.text = NSLocalizedStringFromTable(@"No Photos", @"UzysAssetsPickerController",nil);
  393. UILabel *msg = (UILabel *)[weakSelf.noAssetView viewWithTag:kTagNoAssetViewMsgLabel];
  394. msg.text = NSLocalizedStringFromTable(@"You can sync photos onto your iPhone using iTunes.",@"UzysAssetsPickerController", nil);
  395. };
  396. voidBlock setNoVideo = ^{
  397. UIImageView *imgView = (UIImageView *)[weakSelf.noAssetView viewWithTag:kTagNoAssetViewImageView];
  398. imgView.image = [UIImage imageNamed:@"UzysAssetPickerController.bundle/uzysAP_ico_no_video"];
  399. //NSLog(@"no video");
  400. UILabel *title = (UILabel *)[weakSelf.noAssetView viewWithTag:kTagNoAssetViewTitleLabel];
  401. title.text = NSLocalizedStringFromTable(@"No Videos", @"UzysAssetsPickerController",nil);
  402. UILabel *msg = (UILabel *)[weakSelf.noAssetView viewWithTag:kTagNoAssetViewMsgLabel];
  403. msg.text = NSLocalizedStringFromTable(@"You can sync videos onto your iPhone using iTunes.",@"UzysAssetsPickerController", nil);
  404. };
  405. if(self.assets.count ==0)
  406. {
  407. self.noAssetView.hidden = NO;
  408. if(self.segmentedControl.hidden == NO)
  409. {
  410. if(self.segmentedControl.selectedSegmentIndex ==0)
  411. {
  412. setNoImage();
  413. }
  414. else
  415. {
  416. setNoVideo();
  417. }
  418. }
  419. else
  420. {
  421. if(self.maximumNumberOfSelectionMedia >0)
  422. {
  423. UIImageView *imgView = (UIImageView *)[self.noAssetView viewWithTag:kTagNoAssetViewImageView];
  424. imgView.image = [UIImage imageNamed:@"UzysAssetPickerController.bundle/uzysAP_ico_no_image"];
  425. //NSLog(@"no media");
  426. UILabel *title = (UILabel *)[self.noAssetView viewWithTag:kTagNoAssetViewTitleLabel];
  427. title.text = NSLocalizedStringFromTable(@"No Videos", @"UzysAssetsPickerController",nil);
  428. UILabel *msg = (UILabel *)[self.noAssetView viewWithTag:kTagNoAssetViewMsgLabel];
  429. msg.text = NSLocalizedStringFromTable(@"You can sync media onto your iPhone using iTunes.",@"UzysAssetsPickerController", nil);
  430. }
  431. else if(self.maximumNumberOfSelectionPhoto == 0)
  432. {
  433. setNoVideo();
  434. }
  435. else if(self.maximumNumberOfSelectionVideo == 0)
  436. {
  437. setNoImage();
  438. }
  439. }
  440. }
  441. else
  442. {
  443. self.noAssetView.hidden = YES;
  444. }
  445. }
  446. #pragma mark - Collection View Data Source
  447. - (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView
  448. {
  449. return 1;
  450. }
  451. - (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
  452. {
  453. return self.assets.count;
  454. }
  455. - (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
  456. {
  457. static NSString *CellIdentifier = kAssetsViewCellIdentifier;
  458. UzysAssetsViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:CellIdentifier forIndexPath:indexPath];
  459. [cell applyData:[self.assets objectAtIndex:indexPath.row]];
  460. return cell;
  461. }
  462. #pragma mark - Collection View Delegate
  463. - (BOOL)collectionView:(UICollectionView *)collectionView shouldSelectItemAtIndexPath:(NSIndexPath *)indexPath
  464. {
  465. return ([collectionView indexPathsForSelectedItems].count < self.maximumNumberOfSelection);
  466. }
  467. - (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
  468. {
  469. [self setAssetsCountWithSelectedIndexPaths:collectionView.indexPathsForSelectedItems];
  470. }
  471. - (void)collectionView:(UICollectionView *)collectionView didDeselectItemAtIndexPath:(NSIndexPath *)indexPath
  472. {
  473. [self setAssetsCountWithSelectedIndexPaths:collectionView.indexPathsForSelectedItems];
  474. }
  475. #pragma mark - Actions
  476. - (void)finishPickingAssets
  477. {
  478. NSMutableArray *assets = [[NSMutableArray alloc] init];
  479. for (NSIndexPath *indexPath in self.collectionView.indexPathsForSelectedItems)
  480. {
  481. [assets addObject:[self.assets objectAtIndex:indexPath.item]];
  482. }
  483. if([assets count]>0)
  484. {
  485. UzysAssetsPickerController *picker = (UzysAssetsPickerController *)self;
  486. if([picker.delegate respondsToSelector:@selector(UzysAssetsPickerController:didFinishPickingAssets:)])
  487. [picker.delegate UzysAssetsPickerController:picker didFinishPickingAssets:assets];
  488. [self dismissViewControllerAnimated:YES completion:^{
  489. }];
  490. }
  491. }
  492. #pragma mark - Notification
  493. - (void)assetsLibraryUpdated:(NSNotification *)notification
  494. {
  495. dispatch_async(dispatch_get_main_queue(), ^{
  496. //recheck here
  497. if([notification.name isEqualToString:ALAssetsLibraryChangedNotification])
  498. {
  499. NSDictionary* info = [notification userInfo];
  500. NSSet *updatedAssets = [info objectForKey:ALAssetLibraryUpdatedAssetsKey];
  501. NSSet *updatedAssetGroup = [info objectForKey:ALAssetLibraryUpdatedAssetGroupsKey];
  502. NSSet *deletedAssetGroup = [info objectForKey:ALAssetLibraryDeletedAssetGroupsKey];
  503. NSSet *insertedAssetGroup = [info objectForKey:ALAssetLibraryInsertedAssetGroupsKey];
  504. // NSLog(@"updated assets:%@", updatedAssets);
  505. // NSLog(@"updated asset group:%@", updatedAssetGroup);
  506. // NSLog(@"deleted asset group:%@", deletedAssetGroup);
  507. // NSLog(@"inserted asset group:%@", insertedAssetGroup);
  508. if(notification.userInfo == nil)
  509. {
  510. //AllClear
  511. [self setupGroup:nil withSetupAsset:YES];
  512. return;
  513. }
  514. if(insertedAssetGroup.count >0 || deletedAssetGroup.count > 0)
  515. {
  516. [self setupGroup:nil withSetupAsset:NO];
  517. return;
  518. }
  519. if(notification.userInfo.count == 0) {
  520. return;
  521. }
  522. if(updatedAssets.count <2 && updatedAssetGroup.count ==0 && deletedAssetGroup.count == 0 && insertedAssetGroup.count == 0) //이미지픽커에서 앨범에 저장할 경우.
  523. {
  524. [self.assetsLibrary assetForURL:[updatedAssets allObjects][0] resultBlock:^(ALAsset *asset) {
  525. dispatch_async(dispatch_get_main_queue(), ^{
  526. if([[[self.assets[0] valueForProperty:ALAssetPropertyAssetURL] absoluteString] isEqualToString:[[asset valueForProperty:ALAssetPropertyAssetURL] absoluteString]])
  527. {
  528. NSIndexPath *newPath = [NSIndexPath indexPathForRow:0 inSection:0];
  529. [self.collectionView selectItemAtIndexPath:newPath animated:NO scrollPosition:UICollectionViewScrollPositionNone];
  530. [self setAssetsCountWithSelectedIndexPaths:self.collectionView.indexPathsForSelectedItems];
  531. }
  532. });
  533. } failureBlock:nil];
  534. return;
  535. }
  536. NSMutableArray *selectedItems = [NSMutableArray array];
  537. NSArray *selectedPath = self.collectionView.indexPathsForSelectedItems;
  538. for (NSIndexPath *idxPath in selectedPath)
  539. {
  540. [selectedItems addObject:[self.assets objectAtIndex:idxPath.row]];
  541. }
  542. NSInteger beforeAssets = self.assets.count;
  543. [self setupAssets:^{
  544. for (ALAsset *item in selectedItems)
  545. {
  546. for(ALAsset *asset in self.assets)
  547. {
  548. if([[[asset valueForProperty:ALAssetPropertyAssetURL] absoluteString] isEqualToString:[[item valueForProperty:ALAssetPropertyAssetURL] absoluteString]])
  549. {
  550. NSUInteger idx = [self.assets indexOfObject:asset];
  551. NSIndexPath *newPath = [NSIndexPath indexPathForRow:idx inSection:0];
  552. [self.collectionView selectItemAtIndexPath:newPath animated:NO scrollPosition:UICollectionViewScrollPositionNone];
  553. }
  554. }
  555. }
  556. [self setAssetsCountWithSelectedIndexPaths:self.collectionView.indexPathsForSelectedItems];
  557. if(self.assets.count > beforeAssets)
  558. {
  559. [self.collectionView setContentOffset:CGPointMake(0, 0) animated:NO];
  560. }
  561. }];
  562. }
  563. });
  564. }
  565. #pragma mark - Property
  566. - (void)setTitle:(NSString *)title
  567. {
  568. [super setTitle:title];
  569. [self.btnTitle setTitle:title forState:UIControlStateNormal];
  570. //NSLog(@" x %f %f %f",self.btnTitle.titleLabel.frame.origin.x,self.btnTitle.titleLabel.bounds.size.width,self.btnTitle.imageView.bounds.size.width);
  571. //这里不对按钮内部做UI调整了 这样的话 虽然图片在标题前 不过 不会太丑 oh^真棒
  572. // [self.btnTitle setImageEdgeInsets:UIEdgeInsetsMake(5, self.btnTitle.frame.origin.x + self.btnTitle.frame.size.width + self.btnTitle.imageView.bounds.size.width, 0, 0)];
  573. // [self.btnTitle setTitleEdgeInsets:UIEdgeInsetsMake(5, 0, 0, 0)];
  574. [self.btnTitle layoutIfNeeded];
  575. }
  576. - (void)menuArrowRotate
  577. {
  578. [UIView animateWithDuration:0.35 animations:^{
  579. if(self.groupPicker.isOpen)
  580. {
  581. //在这里 改变添加图片的样式
  582. self.btnTitle.imageView.transform = CGAffineTransformMakeRotation(M_PI);
  583. }
  584. else
  585. {
  586. self.btnTitle.imageView.transform = CGAffineTransformIdentity;
  587. }
  588. } completion:^(BOOL finished) {
  589. }];
  590. }
  591. #pragma mark - Control Action
  592. - (IBAction)btnAction:(id)sender {
  593. UIButton *btn = (UIButton *)sender;
  594. switch (btn.tag) {
  595. case kTagButtonCamera:
  596. {
  597. if (![UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) {
  598. UIAlertView *myAlertView = [[UIAlertView alloc] initWithTitle:@"提示"
  599. message:@"照相机暂不可用"
  600. delegate:nil
  601. cancelButtonTitle:@"确定"
  602. otherButtonTitles: nil];
  603. [myAlertView show];
  604. }
  605. else
  606. {
  607. // [self initImagePicker];
  608. __weak typeof(self) weakSelf = self;
  609. [self presentViewController:self.picker animated:YES completion:^{
  610. //카메라 화면으로 가면 강제로 가메라 롤로 변경.被迫到相机胶卷,相机屏幕的变化
  611. if(![weakSelf.assetsGroup isEqual:weakSelf.groups[0]] )
  612. {
  613. weakSelf.assetsGroup = weakSelf.groups[0];
  614. [weakSelf changeGroup:0 filter:weakSelf.assetsFilter];
  615. }
  616. }];
  617. }
  618. }
  619. break;
  620. case kTagButtonClose:
  621. {
  622. if([self.delegate respondsToSelector:@selector(UzysAssetsPickerControllerDidCancel:)])
  623. {
  624. }
  625. [self dismissViewControllerAnimated:YES completion:^{
  626. }];
  627. }
  628. break;
  629. case kTagButtonGroupPicker:
  630. {
  631. [self.groupPicker toggle];
  632. [self menuArrowRotate];
  633. }
  634. break;
  635. case kTagButtonDone:
  636. [self finishPickingAssets];
  637. break;
  638. default:
  639. break;
  640. }
  641. }
  642. - (IBAction)indexDidChangeForSegmentedControl:(id)sender {
  643. UISegmentedControl *segmentedControl = (UISegmentedControl *) sender;
  644. NSInteger selectedSegment = segmentedControl.selectedSegmentIndex;
  645. if(selectedSegment ==0)
  646. {
  647. [self changeAssetType:YES endBlock:nil];
  648. }
  649. else
  650. {
  651. [self changeAssetType:NO endBlock:nil];
  652. }
  653. }
  654. #pragma mark - UIImagerPickerDelegate
  655. - (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
  656. {
  657. /*
  658. iOS8之后 调用系统相机 有时候会遇到这个问题 查了不少资料 遇到的人也蛮多的 不过没遇到有严重影响的 danson
  659. Snapshotting a view that has not been rendered results in an empty snapshot. Ensure your view has been rendered at least once before snapshotting or snapshot after screen updates
  660. */
  661. __weak typeof(self) weakSelf = self;
  662. //사진 촬영 시 照片拍摄
  663. if (CFStringCompare((CFStringRef) [info objectForKey:UIImagePickerControllerMediaType], kUTTypeImage, 0) == kCFCompareEqualTo)
  664. {
  665. if(self.segmentedControl.selectedSegmentIndex ==1)
  666. {
  667. self.segmentedControl.selectedSegmentIndex = 0;
  668. self.maximumNumberOfSelection = weakSelf.maximumNumberOfSelectionPhoto;
  669. if(self.segmentedControl.hidden ==NO)
  670. self.assetsFilter = [ALAssetsFilter allPhotos];
  671. }
  672. UIImage *image = info[UIImagePickerControllerOriginalImage];
  673. [self.assetsLibrary writeImageToSavedPhotosAlbum:image.CGImage metadata:info[UIImagePickerControllerMediaMetadata] completionBlock:^(NSURL *assetURL, NSError *error) {
  674. //NSLog(@"writeImageToSavedPhotosAlbum");
  675. }];
  676. }
  677. else //비디오 촬영시 视频拍摄
  678. {
  679. if(self.segmentedControl.selectedSegmentIndex ==0)
  680. {
  681. self.segmentedControl.selectedSegmentIndex = 1;
  682. self.maximumNumberOfSelection = self.maximumNumberOfSelectionVideo;
  683. if(self.segmentedControl.hidden ==NO)
  684. self.assetsFilter = [ALAssetsFilter allVideos];
  685. }
  686. [self.assetsLibrary writeVideoAtPathToSavedPhotosAlbum:info[UIImagePickerControllerMediaURL] completionBlock:^(NSURL *assetURL, NSError *error) {
  687. }];
  688. }
  689. [picker dismissViewControllerAnimated:YES completion:^{}];
  690. }
  691. - (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker
  692. {
  693. [picker dismissViewControllerAnimated:YES completion:^{
  694. }];
  695. }
  696. #pragma mark - UIViewController Property
  697. - (UIStatusBarStyle)preferredStatusBarStyle
  698. {
  699. return UIStatusBarStyleDefault;
  700. }
  701. - (UIViewController *)childViewControllerForStatusBarHidden
  702. {
  703. return nil;
  704. }
  705. - (BOOL)prefersStatusBarHidden
  706. {
  707. return NO;
  708. }
  709. -(NSUInteger)supportedInterfaceOrientations
  710. {
  711. return UIInterfaceOrientationMaskPortrait;
  712. }
  713. - (UIInterfaceOrientation)preferredInterfaceOrientationForPresentation
  714. {
  715. return UIInterfaceOrientationPortrait;
  716. }
  717. @end