-
Notifications
You must be signed in to change notification settings - Fork 36
/
Copy pathWPMediaPickerViewController.m
1604 lines (1360 loc) · 61.1 KB
/
WPMediaPickerViewController.m
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#import "WPMediaPickerViewController.h"
#import "WPMediaCollectionViewCell.h"
#import "WPMediaCapturePreviewCollectionView.h"
#import "WPMediaPickerViewController.h"
#import "WPMediaGroupPickerViewController.h"
#import "WPPHAssetDataSource.h"
#import "WPMediaCapturePresenter.h"
#import "WPInputMediaPickerViewController.h"
#import "WPCarouselAssetsViewController.h"
#import "UIViewController+MediaAdditions.h"
@import MobileCoreServices;
@import AVFoundation;
static CGFloat const IPhoneSELandscapeWidth = 568.0f;
static CGFloat const IPhone7PortraitWidth = 375.0f;
static CGFloat const IPhone7LandscapeWidth = 667.0f;
static CGFloat const IPadPortraitWidth = 768.0f;
static CGFloat const IPadLandscapeWidth = 1024.0f;
static CGFloat const IPadPro12LandscapeWidth = 1366.0f;
static NSString *const CustomHeaderReuseIdentifier = @"CustomHeaderReuseIdentifier";
@interface WPMediaPickerViewController ()
<
UICollectionViewDataSource,
UICollectionViewDelegate,
UIImagePickerControllerDelegate,
UINavigationControllerDelegate,
UICollectionViewDelegateFlowLayout,
UISearchBarDelegate
>
@property (nonatomic, readonly) UICollectionViewFlowLayout *layout;
@property (nonatomic, strong) NSMutableArray *internalSelectedAssets;
@property (nonatomic, strong) id<WPMediaAsset> capturedAsset;
@property (nonatomic, strong) WPMediaCapturePreviewCollectionView *captureCell;
@property (nonatomic, strong) WPMediaCapturePresenter *capturePresenter;
@property (nonatomic, strong) UIRefreshControl *refreshControl;
@property (nonatomic, strong) NSObject *changesObserver;
@property (nonatomic, strong) NSIndexPath *firstVisibleCell;
@property (nonatomic, assign) BOOL refreshGroupFirstTime;
@property (nonatomic, strong) UILongPressGestureRecognizer *longPressGestureRecognizer;
@property (nonatomic, strong) NSIndexPath *assetIndexInPreview;
@property (nonatomic, strong, nullable) Class overlayViewClass;
@property (nonatomic, strong, readwrite) UISearchBar *searchBar;
@property (nonatomic, strong) NSLayoutConstraint *searchBarTopConstraint;
@property (nonatomic, assign) CGFloat currentKeyboardHeight;
@property (nonatomic, strong) UIView *emptyView;
@property (nonatomic, strong) UIView *emptyViewContainer;
@property (nonatomic, strong) UILabel *defaultEmptyView;
@property (nonatomic, strong) UIViewController *emptyViewController;
@property (nonatomic, strong) UIViewController *defaultEmptyViewController;
@property (nonatomic, strong) NSLayoutConstraint *emptyViewBottomConstraint;
@property (nonatomic, strong) WPActionBar *accessoryActionBar;
@property (nonatomic, strong) UIButton *selectedActionButton;
@property (nonatomic, strong) UIButton *previewActionButton;
/**
The size of the camera preview cell
*/
@property (nonatomic, assign) CGSize cameraPreviewSize;
@end
@implementation WPMediaPickerViewController
static CGFloat SelectAnimationTime = 0.2;
- (instancetype)init
{
return [self initWithOptions:[WPMediaPickerOptions new]];
}
- (instancetype)initWithOptions:(WPMediaPickerOptions *)options {
self = [super initWithNibName:nil bundle:nil];
if (self) {
UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init];
_collectionView = [[UICollectionView alloc] initWithFrame:(CGRectZero) collectionViewLayout:layout];
_internalSelectedAssets = [[NSMutableArray alloc] init];
_capturedAsset = nil;
_options = [options copy];
_refreshGroupFirstTime = YES;
_longPressGestureRecognizer = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(handleLongPressOnAsset:)];
_viewControllerToUseToPresent = self;
}
return self;
}
- (void)dealloc
{
[self unregisterDataSourceObservers];
}
- (void)viewDidLoad
{
[super viewDidLoad];
// Setup subviews
[self setupPullToRefresh];
[self addCollectionViewToView];
[self setupCollectionView];
[self setupSearchBar];
[self setupLayout];
[self addEmptyViewContainer];
//setup data
[self.dataSource setMediaTypeFilter:self.options.filter];
[self.dataSource setAscendingOrdering:!self.options.showMostRecentFirst];
[self.view addGestureRecognizer:self.longPressGestureRecognizer];
self.layout.sectionInsetReference = UICollectionViewFlowLayoutSectionInsetFromSafeArea;
[self refreshDataAnimated:NO];
}
- (void)setupPullToRefresh
{
self.refreshControl = [[UIRefreshControl alloc] init];
[self.refreshControl addTarget:self action:@selector(pullToRefresh:) forControlEvents:UIControlEventValueChanged];
[self.collectionView addSubview:self.refreshControl];
}
- (void)registerDataSourceObservers {
__weak __typeof__(self) weakSelf = self;
self.changesObserver = [self.dataSource registerChangeObserverBlock:
^(BOOL incrementalChanges, NSIndexSet *removed, NSIndexSet *inserted, NSIndexSet *changed, NSArray *moves) {
// If the view is not loaded or a refresh of data is going on, ignore changes on the data in the meantime.
if (!weakSelf.isViewLoaded || weakSelf.refreshGroupFirstTime || weakSelf.refreshControl.isRefreshing) {
return;
}
if (incrementalChanges) {
/// Avoid NSInternalInconsistencyException crash by wrapping performBatchUpdates in the try catch block.
///
/// Apple documentation indicates if the collection view’s layout isn’t up to date before you call performBatchUpdates,
/// additional reload may occur that can cause problems. Developers should update the data model inside the updates
/// block or ensure the layout is updated before calling performBatchUpdates.
/// However, MediaLibraryPickerDataSource reloads the data source before view controller gets informed about updates,
/// creating a possibility for a crash.
/// https://developer.apple.com/documentation/uikit/uicollectionview/1618045-performbatchupdates
///
/// Apple engineers reiterate this fact and point out the best way to avoid this issue is to adopt
/// UICollectionViewDiffableDataSource which requires refactoring of the current solution
/// https://developer.apple.com/forums/thread/728797?answerId=751887022#751887022
@try {
[weakSelf updateDataWithRemoved:removed inserted:inserted changed:changed moved:moves];
} @catch (NSException *exception) {
[weakSelf.collectionView reloadData];
}
} else {
[weakSelf.collectionView reloadData];
}
}];
}
- (void)unregisterDataSourceObservers {
if (_changesObserver) {
[_dataSource unregisterChangeObserver:_changesObserver];
}
}
- (void)setDataSource:(id<WPMediaCollectionDataSource>)dataSource {
[self unregisterDataSourceObservers];
_dataSource = dataSource;
[self registerDataSourceObservers];
}
- (void)setOptions:(WPMediaPickerOptions *)options {
WPMediaPickerOptions *originalOptions = _options;
_options = [options copy];
if (!self.viewLoaded) {
return;
}
[self.dataSource setMediaTypeFilter:options.filter];
[self.dataSource setAscendingOrdering:!options.showMostRecentFirst];
self.collectionView.allowsMultipleSelection = options.allowMultipleSelection;
self.collectionView.alwaysBounceHorizontal = !options.scrollVertically;
self.collectionView.alwaysBounceVertical = options.scrollVertically;
BOOL refreshNeeded = (originalOptions.filter != options.filter) ||
(originalOptions.showMostRecentFirst != options.showMostRecentFirst) ||
(originalOptions.allowCaptureOfMedia != options.allowCaptureOfMedia);
if (refreshNeeded) {
[self refreshDataAnimated:NO];
} else {
// if just the selection mode changed we just need to reload the collection view not all the data.
if (originalOptions.allowMultipleSelection != options.allowMultipleSelection || options.allowCaptureOfMedia != originalOptions.allowCaptureOfMedia) {
[self.collectionView reloadData];
}
}
[self setupSearchBar];
}
- (void)registerClassForReusableCellOverlayViews:(Class)overlayClass
{
NSParameterAssert([overlayClass isSubclassOfClass:[UIView class]]);
self.overlayViewClass = overlayClass;
}
- (void)registerClassForCustomHeaderView:(Class)overlayClass
{
NSParameterAssert([overlayClass isSubclassOfClass:[UICollectionReusableView class]]);
[self.collectionView registerClass:overlayClass
forSupplementaryViewOfKind:UICollectionElementKindSectionHeader
withReuseIdentifier:CustomHeaderReuseIdentifier];
}
- (UICollectionViewFlowLayout *)layout
{
return (UICollectionViewFlowLayout *)self.collectionView.collectionViewLayout;
}
- (void)setupLayout
{
CGFloat photoSpacing = 1.0f;
CGFloat photoSize;
UICollectionViewFlowLayout *layout = self.layout;
CGFloat frameWidth = self.view.frame.size.width;
CGFloat frameHeight = self.view.frame.size.width - self.view.safeAreaInsets.bottom - self.view.safeAreaInsets.top;
CGFloat dimensionToUse;
if (self.options.scrollVertically) {
dimensionToUse = frameWidth;
layout.scrollDirection = UICollectionViewScrollDirectionVertical;
layout.sectionInset = UIEdgeInsetsMake(2, 0, 0, 0);
} else {
dimensionToUse = frameHeight;
layout.scrollDirection = UICollectionViewScrollDirectionHorizontal;
layout.sectionInset = UIEdgeInsetsMake(5, 0, 5, 0);
}
NSUInteger numberOfPhotosForLine = [self numberOfPhotosPerRow:dimensionToUse];
photoSize = [self cellSizeForPhotosPerLineCount:numberOfPhotosForLine
photoSpacing:photoSpacing
frameWidth:dimensionToUse];
self.cameraPreviewSize = CGSizeMake(photoSize, photoSize);
layout.itemSize = CGSizeMake(photoSize, photoSize);
layout.minimumLineSpacing = photoSpacing;
layout.minimumInteritemSpacing = photoSpacing;
[self resetContentInset];
[self.view layoutIfNeeded];
}
- (void)resetContentInset
{
CGFloat searchBarHeight = self.searchBar.bounds.size.height;
self.additionalSafeAreaInsets = UIEdgeInsetsMake(searchBarHeight, 0, 0, 0);
self.searchBarTopConstraint.constant = self.view.safeAreaInsets.top - searchBarHeight;
}
- (CGFloat)cellSizeForPhotosPerLineCount:(NSUInteger)photosPerLine photoSpacing:(CGFloat)photoSpacing frameWidth:(CGFloat)frameWidth
{
CGFloat totalSpacing = (photosPerLine - 1) * photoSpacing;
return floorf((frameWidth - totalSpacing) / photosPerLine);
}
/**
Given the provided frame width, this method returns a progressively increasing number of photos
to be used in a picker row.
@param frameWidth Width of the frame containing the picker
@return The number of photo cells to be used in a row. Defaults to 3.
*/
- (NSUInteger)numberOfPhotosPerRow:(CGFloat)frameWidth {
NSUInteger numberOfPhotos = 3;
if (frameWidth >= IPhone7PortraitWidth && frameWidth < IPhoneSELandscapeWidth) {
numberOfPhotos = 4;
} else if (frameWidth >= IPhoneSELandscapeWidth && frameWidth < IPhone7LandscapeWidth) {
numberOfPhotos = 5;
} else if (frameWidth >= IPhone7LandscapeWidth && frameWidth < IPadPortraitWidth) {
numberOfPhotos = 6;
} else if (frameWidth >= IPadPortraitWidth && frameWidth < IPadLandscapeWidth) {
numberOfPhotos = 7;
} else if (frameWidth >= IPadLandscapeWidth && frameWidth < IPadPro12LandscapeWidth) {
numberOfPhotos = 9;
} else if (frameWidth >= IPadPro12LandscapeWidth) {
numberOfPhotos = 12;
}
return numberOfPhotos;
}
- (void)viewDidLayoutSubviews {
[super viewDidLayoutSubviews];
[self setupLayout];
}
- (void)viewWillDisappear:(BOOL)animated {
[super viewWillDisappear:animated];
[self.captureCell stopCaptureOnCompletion:nil];
}
- (void)viewWillAppear:(BOOL)animated {
[super viewWillAppear:animated];
[self.captureCell startCapture];
[self registerForKeyboardNotifications];
[self updateActionbar];
}
- (void)viewDidDisappear:(BOOL)animated
{
[super viewDidDisappear:animated];
[self unregisterForKeyboardNotifications];
}
- (void)traitCollectionDidChange:(UITraitCollection *)previousTraitCollection
{
[super traitCollectionDidChange:previousTraitCollection];
if ([self shouldShowCustomHeaderView]) {
// If there's a custom header, we'll invalidate it so that it can adapt itself to dynamic type changes.
UICollectionViewFlowLayoutInvalidationContext *context = [UICollectionViewFlowLayoutInvalidationContext new];
[context invalidateSupplementaryElementsOfKind:UICollectionElementKindSectionHeader atIndexPaths:@[ [NSIndexPath indexPathForRow:0 inSection:0] ]];
[self.collectionView.collectionViewLayout invalidateLayout];
}
}
- (UIViewController *)viewControllerToUseToPresent
{
// viewControllerToUseToPresent defaults to self but could be set to nil. Reset to self if needed.
if (!_viewControllerToUseToPresent) {
_viewControllerToUseToPresent = self;
}
return _viewControllerToUseToPresent;
}
- (void)setupCollectionView
{
self.collectionView.dataSource = self;
self.collectionView.delegate = self;
self.collectionView.allowsSelection = YES;
self.collectionView.allowsMultipleSelection = self.options.allowMultipleSelection;
self.collectionView.bounces = YES;
self.collectionView.alwaysBounceHorizontal = !self.options.scrollVertically;
self.collectionView.alwaysBounceVertical = self.options.scrollVertically;
self.collectionView.accessibilityIdentifier = @"MediaCollection";
// Register cell classes
[self.collectionView registerClass:[WPMediaCollectionViewCell class]
forCellWithReuseIdentifier:NSStringFromClass([WPMediaCollectionViewCell class])];
[self.collectionView registerClass:[WPMediaCapturePreviewCollectionView class]
forSupplementaryViewOfKind:UICollectionElementKindSectionHeader
withReuseIdentifier:NSStringFromClass([WPMediaCapturePreviewCollectionView class])];
[self.collectionView registerClass:[WPMediaCapturePreviewCollectionView class]
forSupplementaryViewOfKind:UICollectionElementKindSectionFooter
withReuseIdentifier:NSStringFromClass([WPMediaCapturePreviewCollectionView class])];
}
- (void)addCollectionViewToView
{
self.collectionView.translatesAutoresizingMaskIntoConstraints = NO;
[self.view addSubview:self.collectionView];
[NSLayoutConstraint activateConstraints:
@[
[self.collectionView.topAnchor constraintEqualToAnchor:self.view.topAnchor],
[self.collectionView.bottomAnchor constraintEqualToAnchor:self.view.bottomAnchor],
[self.collectionView.leadingAnchor constraintEqualToAnchor:self.view.leadingAnchor],
[self.collectionView.trailingAnchor constraintEqualToAnchor:self.view.trailingAnchor]
]
];
}
- (void)setupSearchBar
{
BOOL shouldShowSearchBar = self.options.showSearchBar &&
![self.parentViewController isKindOfClass:[WPInputMediaPickerViewController class]] && //Disable search bar on WPInputMediaPicker
[self.dataSource respondsToSelector:@selector(searchFor:)];
if (shouldShowSearchBar && self.searchBar == nil) {
self.searchBar = [[UISearchBar alloc] init];
self.searchBar.delegate = self;
self.searchBar.translatesAutoresizingMaskIntoConstraints = NO;
[self addSearchBarToView];
} else if (!shouldShowSearchBar && self.searchBar) {
[self hideSearchBar];
}
}
- (void)showSearchBar
{
[self setupSearchBar];
}
- (void)hideSearchBar
{
[self.searchBar removeFromSuperview];
self.searchBar = nil;
}
- (void)addSearchBarToView
{
[self.searchBar sizeToFit];
[self.view addSubview:self.searchBar];
self.searchBarTopConstraint = [self.searchBar.topAnchor constraintEqualToAnchor:self.view.topAnchor];
[NSLayoutConstraint activateConstraints:
@[
self.searchBarTopConstraint,
[self.searchBar.leadingAnchor constraintEqualToAnchor:self.view.leadingAnchor],
[self.searchBar.trailingAnchor constraintEqualToAnchor:self.view.trailingAnchor]
]
];
}
- (UIStatusBarStyle)preferredStatusBarStyle {
return self.options.preferredStatusBarStyle;
}
#pragma mark - Action bar
- (UIView *)actionBar
{
return self.accessoryActionBar;
}
- (WPActionBar *)accessoryActionBar
{
if (_accessoryActionBar) {
return _accessoryActionBar;
}
_accessoryActionBar = [[WPActionBar alloc] init];
[_accessoryActionBar addLeftButton:self.previewActionButton];
[_accessoryActionBar addRightButton:self.selectedActionButton];
[_accessoryActionBar sizeToFit];
return _accessoryActionBar;
}
- (UIButton *)previewActionButton
{
if (_previewActionButton) {
return _previewActionButton;
}
_previewActionButton = [UIButton buttonWithType:(UIButtonTypeSystem)];
[_previewActionButton addTarget:self action:@selector(onPreviewButtonPressed:) forControlEvents:UIControlEventTouchUpInside];
[_previewActionButton setTitle:self.previewActionTitle forState:UIControlStateNormal];
_previewActionButton.accessibilityIdentifier = @"PreviewButton";
return _previewActionButton;
}
- (UIButton *)selectedActionButton
{
if (_selectedActionButton) {
return _selectedActionButton;
}
_selectedActionButton = [UIButton buttonWithType:(UIButtonTypeSystem)];
UIFont *font = _selectedActionButton.titleLabel.font;
_selectedActionButton.titleLabel.font = [UIFont boldSystemFontOfSize:font.pointSize];
[_selectedActionButton addTarget:self action:@selector(onAddButtonPressed:) forControlEvents:UIControlEventTouchUpInside];
[_selectedActionButton setTitle:self.selectionActionTitle forState:UIControlStateNormal];
_selectedActionButton.accessibilityIdentifier = @"SelectedActionButton";
return _selectedActionButton;
}
- (NSString *)previewActionTitle
{
NSString *actionString = _previewActionTitle;
if (actionString == nil) {
actionString = NSLocalizedString(@"Preview %@", @"Action for Media Picker to preview the selected media items. The argument in the string represents the number of elements (as numeric digits) selected");
}
return [self formatButtonTitleWithTitlePlaceholder:actionString];
}
- (NSString *)selectionActionTitle
{
NSString *actionString = _selectionActionTitle;
if (actionString == nil) {
actionString = NSLocalizedString(@"Add %@", @"Action for Media Picker to indicate selection of media. The argument in the string represents the number of elements (as numeric digits) selected");
}
return [self formatButtonTitleWithTitlePlaceholder:actionString];
}
- (NSString *)formatButtonTitleWithTitlePlaceholder:(NSString *)placeholder
{
NSString * countString = @(self.internalSelectedAssets.count).stringValue;
return [NSString stringWithFormat:placeholder, countString];
}
- (void)updateActionbar
{
if ([self shouldShowActionBar]) {
[UIView performWithoutAnimation:^{
[self.previewActionButton setTitle:self.previewActionTitle forState:UIControlStateNormal];
[self.selectedActionButton setTitle:self.selectionActionTitle forState:UIControlStateNormal];
[self.previewActionButton layoutIfNeeded];
[self.selectedActionButton layoutIfNeeded];
}];
if ([self.searchBar isFirstResponder]) {
[self.searchBar reloadInputViews];
} else {
[self becomeFirstResponder];
}
} else {
if ([self isFirstResponder]) {
[self resignFirstResponder];
} else {
[self.searchBar reloadInputViews];
}
}
}
- (BOOL)canBecomeFirstResponder
{
return [self shouldShowActionBar];
}
- (UIView *)inputAccessoryView
{
if ([self shouldShowActionBar]) {
return self.accessoryActionBar;
}
return nil;
}
- (BOOL)shouldShowActionBar
{
return self.options.showActionBar && self.options.allowMultipleSelection && self.internalSelectedAssets.count > 0;
}
- (void)onPreviewButtonPressed:(UIBarButtonItem *)sender
{
UIViewController *previewController = [self previewViewControllerForAsset:[self.selectedAssets firstObject]];
[self displayPreviewController:previewController];
}
- (void)onAddButtonPressed:(UIBarButtonItem *)sender
{
if ([self.mediaPickerDelegate respondsToSelector:@selector(mediaPickerController:didFinishPickingAssets:)]) {
[self.mediaPickerDelegate mediaPickerController:self didFinishPickingAssets:[self.internalSelectedAssets copy]];
}
}
#pragma mark - Actions
- (void)pullToRefresh:(id)sender
{
[self refreshData];
}
- (BOOL)isShowingCaptureCell
{
return self.options.allowCaptureOfMedia && [WPMediaCapturePresenter isCaptureAvailable] && !self.refreshGroupFirstTime;
}
- (void)clearSelectedAssets:(BOOL)animated
{
for (NSIndexPath *indexPath in [self.collectionView indexPathsForSelectedItems]) {
[self.collectionView deselectItemAtIndexPath:indexPath animated:animated];
}
[self.internalSelectedAssets removeAllObjects];
}
- (void)resetState:(BOOL)animated {
[self clearSelectedAssets:animated];
[self scrollToStart:animated];
}
- (void)scrollToStart:(BOOL)animated {
if ([self.dataSource numberOfAssets] == 0) {
return;
}
NSInteger sectionToScroll = 0;
NSInteger itemToScroll = self.options.showMostRecentFirst ? 0 : [self.dataSource numberOfAssets] - 1;
NSIndexPath *indexPath = [NSIndexPath indexPathForItem:itemToScroll inSection:sectionToScroll];
UICollectionViewScrollPosition position = UICollectionViewScrollPositionBottom;
UICollectionViewFlowLayout *layout = (UICollectionViewFlowLayout *)self.collectionView.collectionViewLayout;
if (layout && layout.scrollDirection == UICollectionViewScrollDirectionHorizontal) {
position = UICollectionViewScrollPositionCenteredHorizontally;
}
[self.collectionView scrollToItemAtIndexPath:indexPath
atScrollPosition:position
animated:animated];
}
- (void)showCapture {
[self captureMedia];
return;
}
#pragma mark - Empty View support
/** An empty view container to hold the emptyViewController or emptyView that comes from the delegate
*/
- (void)addEmptyViewContainer
{
self.emptyViewContainer = [[UIView alloc] initWithFrame:self.collectionView.frame];
[self.emptyViewContainer setTranslatesAutoresizingMaskIntoConstraints:NO];
[self.collectionView addSubview:self.emptyViewContainer];
self.emptyViewBottomConstraint = [self.emptyViewContainer.bottomAnchor constraintEqualToAnchor:self.view.bottomAnchor];
[self.emptyViewBottomConstraint setConstant:-self.currentKeyboardHeight];
[NSLayoutConstraint activateConstraints:
@[
[self.emptyViewContainer.topAnchor constraintEqualToAnchor:self.collectionView.topAnchor],
self.emptyViewBottomConstraint,
[self.emptyViewContainer.leadingAnchor constraintEqualToAnchor:self.view.leadingAnchor],
[self.emptyViewContainer.trailingAnchor constraintEqualToAnchor:self.view.trailingAnchor]
]
];
}
- (UIView *)emptyView
{
if (_emptyView) {
return _emptyView;
}
if ([self.mediaPickerDelegate respondsToSelector:@selector(emptyViewForMediaPickerController:)]) {
_emptyView = [self.mediaPickerDelegate emptyViewForMediaPickerController:self];
} else {
_emptyView = [self defaultEmptyView];
}
return _emptyView;
}
/** Checks if the parentViewController is providing a custom empty ViewController to be added, if not, add a provided custom emptyView
*/
- (void)populateEmptyViewContainer
{
if ([self usingEmptyViewController]) {
[self addEmptyViewControllerToContainer];
} else {
[self addEmptyViewToContainer];
}
}
- (UILabel *)defaultEmptyView
{
if (_defaultEmptyView) {
return _defaultEmptyView;
}
_defaultEmptyView = [[UILabel alloc] init];
_defaultEmptyView.text = NSLocalizedString(@"Nothing to show", @"Default message for empty media picker");
[_defaultEmptyView sizeToFit];
return _defaultEmptyView;
}
- (void)addEmptyViewToContainer
{
if (self.emptyView != nil && self.emptyView.superview != nil) {
return;
}
[self.emptyView setTranslatesAutoresizingMaskIntoConstraints:NO];
[self.emptyViewContainer addSubview:self.emptyView];
[NSLayoutConstraint activateConstraints:
@[
[self.emptyView.centerYAnchor constraintEqualToAnchor:self.emptyViewContainer.centerYAnchor],
[self.emptyView.centerXAnchor constraintEqualToAnchor:self.emptyViewContainer.centerXAnchor]
]
];
}
#pragma mark - Empty View Controller support
- (void)addEmptyViewControllerToContainer
{
if (self.emptyViewController != nil && self.emptyViewController.view.superview != nil) {
return;
}
[self addChildViewController:self.emptyViewController];
[self.emptyViewController.view setTranslatesAutoresizingMaskIntoConstraints:NO];
[self.emptyViewContainer addSubview:self.emptyViewController.view];
[NSLayoutConstraint activateConstraints:
@[
[self.emptyViewController.view.topAnchor constraintEqualToAnchor:self.emptyViewContainer.topAnchor],
[self.emptyViewController.view.bottomAnchor constraintEqualToAnchor:self.emptyViewContainer.bottomAnchor],
[self.emptyViewController.view.leadingAnchor constraintEqualToAnchor:self.emptyViewContainer.leadingAnchor],
[self.emptyViewController.view.trailingAnchor constraintEqualToAnchor:self.emptyViewContainer.trailingAnchor]
]
];
[self.emptyViewController didMoveToParentViewController:self];
}
- (UIViewController *)emptyViewController
{
if (_emptyViewController) {
return _emptyViewController;
}
if ([self usingEmptyViewController]) {
_emptyViewController = [self.mediaPickerDelegate emptyViewControllerForMediaPickerController:self];
}
if (_emptyViewController == nil) {
_emptyViewController = self.defaultEmptyViewController;
}
return _emptyViewController;
}
- (UIViewController *)defaultEmptyViewController
{
if (_defaultEmptyViewController) {
return _defaultEmptyViewController;
}
_defaultEmptyViewController = [[UIViewController alloc] init];
UILabel *emptyViewLabel = self.defaultEmptyView;
[emptyViewLabel setTranslatesAutoresizingMaskIntoConstraints:NO];
[[_defaultEmptyViewController view] addSubview:emptyViewLabel];
[NSLayoutConstraint activateConstraints:
@[
[emptyViewLabel.centerYAnchor constraintEqualToAnchor:self.defaultEmptyViewController.view.centerYAnchor],
[emptyViewLabel.centerXAnchor constraintEqualToAnchor:self.defaultEmptyViewController.view.centerXAnchor]
]
];
return _defaultEmptyViewController;
}
- (BOOL)usingEmptyViewController
{
return [self.mediaPickerDelegate respondsToSelector:@selector(emptyViewControllerForMediaPickerController:)];
}
#pragma mark - UICollectionViewDataSource
- (void)updateDataWithRemoved:(NSIndexSet *)removed inserted:(NSIndexSet *)inserted changed:(NSIndexSet *)changed moved:(NSArray<id<WPMediaMove>> *)moves {
if ([removed containsIndex:self.assetIndexInPreview.item]){
self.assetIndexInPreview = nil;
}
__weak __typeof__(self) weakSelf = self;
[self.collectionView performBatchUpdates:^{
if ([removed count] > 0) {
[self.collectionView deleteItemsAtIndexPaths:[self indexPathsFromIndexSet:removed section:0]];
}
if ([inserted count] > 0) {
[self.collectionView insertItemsAtIndexPaths:[self indexPathsFromIndexSet:inserted section:0]];
}
for (id<WPMediaMove> move in moves) {
[self.collectionView moveItemAtIndexPath:[NSIndexPath indexPathForItem:[move from] inSection:0]
toIndexPath:[NSIndexPath indexPathForItem:[move to] inSection:0]];
if (self.assetIndexInPreview.row == move.from) {
self.assetIndexInPreview = [NSIndexPath indexPathForItem:move.to inSection:0];
}
}
} completion:^(BOOL finished) {
if (weakSelf == nil) {
return;
}
[weakSelf refreshSelection];
@try {
// Reloading the changed items here rather than in the batch update block above to fix this issue:
// https://github.com/wordpress-mobile/WordPress-iOS/issues/19505
NSMutableSet<NSIndexPath *> *indexPaths = [NSMutableSet setWithArray:[weakSelf indexPathsFromIndexSet:changed section:0]];
[indexPaths addObjectsFromArray:weakSelf.collectionView.indexPathsForSelectedItems];
[weakSelf.collectionView reloadItemsAtIndexPaths:[indexPaths allObjects]];
} @catch (NSException *exception) {
[weakSelf.collectionView reloadData];
}
}];
}
- (NSArray *)indexPathsFromIndexSet:(NSIndexSet *)indexSet section:(NSInteger)section{
NSMutableArray *indexPaths = [NSMutableArray arrayWithCapacity:indexSet.count];
[indexSet enumerateIndexesUsingBlock:^(NSUInteger idx, BOOL * _Nonnull stop) {
[indexPaths addObject:[NSIndexPath indexPathForItem:idx inSection:section]];
}];
return [NSArray arrayWithArray:indexPaths];
}
- (void)refreshData
{
[self refreshDataAnimated:YES];
}
- (void)refreshDataAnimated:(BOOL)animated
{
// Don't show the refreshControl if emptyViewController is being displayed.
if (! _emptyViewController) {
[self.refreshControl beginRefreshing];
}
self.collectionView.allowsSelection = NO;
self.collectionView.allowsMultipleSelection = NO;
self.collectionView.scrollEnabled = NO;
if ([self.mediaPickerDelegate respondsToSelector:@selector(mediaPickerControllerWillBeginLoadingData:)]) {
[self.mediaPickerDelegate mediaPickerControllerWillBeginLoadingData:self];
}
__weak __typeof__(self) weakSelf = self;
[self.dataSource loadDataWithOptions:WPMediaLoadOptionsAssets success:^{
__typeof__(self) strongSelf = weakSelf;
BOOL refreshGroupFirstTime = strongSelf.refreshGroupFirstTime;
strongSelf.refreshGroupFirstTime = NO;
dispatch_async(dispatch_get_main_queue(), ^{
strongSelf.collectionView.allowsSelection = YES;
strongSelf.collectionView.allowsMultipleSelection = strongSelf.options.allowMultipleSelection;
strongSelf.collectionView.scrollEnabled = YES;
[strongSelf refreshSelection];
[strongSelf.collectionView reloadData];
if (animated) {
[strongSelf.refreshControl endRefreshing];
} else {
[UIView performWithoutAnimation:^{
[strongSelf.refreshControl endRefreshing];
}];
}
// Scroll to the correct position
if (refreshGroupFirstTime){
[strongSelf scrollToStart:NO];
}
[strongSelf informDelegateDidEndLoadingData];
});
} failure:^(NSError *error) {
__typeof__(self) strongSelf = weakSelf;
strongSelf.refreshGroupFirstTime = NO;
dispatch_async(dispatch_get_main_queue(), ^{
[strongSelf informDelegateDidEndLoadingData];
[strongSelf showError:error];
});
}];
}
- (void)informDelegateDidEndLoadingData
{
if ([self.mediaPickerDelegate respondsToSelector:@selector(mediaPickerControllerDidEndLoadingData:)]) {
[self.mediaPickerDelegate mediaPickerControllerDidEndLoadingData:self];
}
}
- (void)showError:(NSError *)error {
[self.refreshControl endRefreshing];
self.collectionView.allowsSelection = YES;
self.collectionView.scrollEnabled = YES;
[self.collectionView reloadData];
if ([self.mediaPickerDelegate respondsToSelector:@selector(mediaPickerController:handleError:)]) {
if ([self.mediaPickerDelegate mediaPickerController:self handleError:error]) {
return;
}
}
[self wpm_showAlertWithError:error okActionHandler:^(UIAlertAction * _Nonnull action) {
if ([self.mediaPickerDelegate respondsToSelector:@selector(mediaPickerControllerDidCancel:)]) {
[self.mediaPickerDelegate mediaPickerControllerDidCancel:self];
}
}];
}
- (void)setSelectedAssets:(NSArray *)selectedAssets {
self.internalSelectedAssets = [selectedAssets copy];
if ([self isViewLoaded]) {
[self refreshDataAnimated: NO];
}
}
- (NSArray *)selectedAssets {
return [self.internalSelectedAssets copy];
}
- (void)refreshSelection
{
NSArray *selectedAssets = [NSArray arrayWithArray:self.internalSelectedAssets];
NSMutableArray *stillExistingSeletedAssets = [NSMutableArray array];
for (id<WPMediaAsset> asset in selectedAssets) {
NSString *assetIdentifier = [asset identifier];
if ([self.dataSource mediaWithIdentifier:assetIdentifier]) {
[stillExistingSeletedAssets addObject:asset];
}
}
if (self.capturedAsset != nil) {
NSString *assetIdentifier = [self.capturedAsset identifier];
if ([self.dataSource mediaWithIdentifier:assetIdentifier]) {
[stillExistingSeletedAssets addObject:self.capturedAsset];
}
NSInteger positionToUpdate = self.options.showMostRecentFirst ? 0 : self.dataSource.numberOfAssets-1;
[self.collectionView selectItemAtIndexPath:[NSIndexPath indexPathForRow:positionToUpdate inSection:0]
animated:NO
scrollPosition:UICollectionViewScrollPositionNone];
self.capturedAsset = nil;
}
self.internalSelectedAssets = stillExistingSeletedAssets;
[self updateActionbar];
if ([self.mediaPickerDelegate respondsToSelector:@selector(mediaPickerController:selectionChanged:)]) {
[self.mediaPickerDelegate mediaPickerController:self selectionChanged:[self.internalSelectedAssets copy]];
}
}
- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView
{
return self.refreshGroupFirstTime ? 0 : 1;
}
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
NSInteger numberOfAssets = [self.dataSource numberOfAssets];
if (self.searchBar.text && [self.mediaPickerDelegate respondsToSelector:@selector(mediaPickerController:didUpdateSearchWithAssetCount:)]) {
[self.mediaPickerDelegate mediaPickerController:self didUpdateSearchWithAssetCount:numberOfAssets];
}
[self toggleEmptyViewFor:numberOfAssets];
return numberOfAssets;
}
- (void)toggleEmptyViewFor:(NSInteger)numberOfAssets
{
if (numberOfAssets > 0) {
[self.emptyViewContainer setHidden: YES];
} else {
[self.emptyViewContainer setHidden: NO];
[self populateEmptyViewContainer];
}
}
- (id<WPMediaAsset>)assetForPosition:(NSIndexPath *)indexPath
{
NSInteger itemPosition = indexPath.item;
NSInteger count = [self.dataSource numberOfAssets];
if (itemPosition >= count || itemPosition < 0) {
return nil;
}
id<WPMediaAsset> asset = [self.dataSource mediaAtIndex:itemPosition];
return asset;
}
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
WPMediaCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:NSStringFromClass([WPMediaCollectionViewCell class]) forIndexPath:indexPath];
[self configureCell:cell forIndexPath:indexPath];
return cell;
}
- (void)configureCell:(WPMediaCollectionViewCell *)cell forIndexPath:(NSIndexPath *)indexPath
{
id<WPMediaAsset> asset = [self assetForPosition:indexPath];
cell.asset = asset;
NSUInteger position = [self positionOfAssetInSelection:asset];
cell.hiddenSelectionIndicator = !self.options.allowMultipleSelection;
[self configureBadgeViewForCell:cell withAsset:asset];
if (position != NSNotFound) {
[self.collectionView selectItemAtIndexPath:indexPath animated:NO scrollPosition:UICollectionViewScrollPositionNone];
if (self.options.allowMultipleSelection) {
[cell setPosition:position + 1];
} else {
[cell setPosition:NSNotFound];
}
cell.selected = YES;
} else {
[cell setPosition:NSNotFound];
cell.selected = NO;
}
}
- (void)configureBadgeViewForCell:(WPMediaCollectionViewCell *)cell withAsset:(id<WPMediaAsset>)asset
{
if (![asset respondsToSelector:@selector(UTTypeIdentifier)]) {
cell.badgeView.hidden = YES;
return;
}
NSString *uttype = [asset UTTypeIdentifier];