UzysAssetsPickerController.m 32 KB

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