-
Notifications
You must be signed in to change notification settings - Fork 1.1k
/
Copy pathMediaLibraryViewController.swift
742 lines (586 loc) · 28.2 KB
/
MediaLibraryViewController.swift
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
import UIKit
import Gridicons
import SVProgressHUD
import WordPressShared
import WPMediaPicker
import MobileCoreServices
/// Displays the user's media library in a grid
///
class MediaLibraryViewController: WPMediaPickerViewController {
fileprivate static let restorationIdentifier = "MediaLibraryViewController"
@objc let blog: Blog
fileprivate let pickerDataSource: MediaLibraryPickerDataSource
fileprivate var isLoading: Bool = false
fileprivate let noResultsView = NoResultsViewController.controller()
fileprivate var selectedAsset: Media? = nil
fileprivate var capturePresenter: WPMediaCapturePresenter?
// After 99% progress, we'll count a media item as being uploaded, and we'll
// show an indeterminate spinner as the server processes it.
fileprivate static let uploadCompleteProgress: Double = 0.99
fileprivate var uploadObserverUUID: UUID?
fileprivate lazy var mediaPickingCoordinator: MediaLibraryMediaPickingCoordinator = {
return MediaLibraryMediaPickingCoordinator(delegate: self)
}()
// MARK: - Initializers
@objc init(blog: Blog) {
WPMediaCollectionViewCell.appearance().placeholderTintColor = .neutral(.shade5)
WPMediaCollectionViewCell.appearance().placeholderBackgroundColor = .neutral(.shade70)
WPMediaCollectionViewCell.appearance().loadingBackgroundColor = .listBackground
self.blog = blog
self.pickerDataSource = MediaLibraryPickerDataSource(blog: blog)
self.pickerDataSource.includeUnsyncedMedia = true
super.init(options: MediaLibraryViewController.pickerOptions())
registerClass(forReusableCellOverlayViews: CircularProgressView.self)
super.restorationIdentifier = MediaLibraryViewController.restorationIdentifier
restorationClass = MediaLibraryViewController.self
self.dataSource = pickerDataSource
self.mediaPickerDelegate = self
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
static func showForBlog(_ blog: Blog, from sourceController: UIViewController) {
let controller = MediaLibraryViewController(blog: blog)
controller.navigationItem.largeTitleDisplayMode = .never
sourceController.navigationController?.pushViewController(controller, animated: true)
QuickStartTourGuide.shared.visited(.blogDetailNavigation)
}
deinit {
unregisterChangeObserver()
unregisterUploadCoordinatorObserver()
}
private class func pickerOptions() -> WPMediaPickerOptions {
let options = WPMediaPickerOptions()
options.showMostRecentFirst = true
options.filter = [.all]
options.allowMultipleSelection = false
options.allowCaptureOfMedia = false
options.showSearchBar = true
options.showActionBar = false
options.badgedUTTypes = [String(kUTTypeGIF)]
options.preferredStatusBarStyle = WPStyleGuide.preferredStatusBarStyle
return options
}
// MARK: - View Loading
override func viewDidLoad() {
super.viewDidLoad()
title = NSLocalizedString("Media", comment: "Title for Media Library section of the app.")
registerChangeObserver()
registerUploadCoordinatorObserver()
noResultsView.configureForNoAssets(userCanUploadMedia: blog.userCanUploadMedia)
noResultsView.delegate = self
updateViewState(for: pickerDataSource.totalAssetCount)
if let collectionView = collectionView {
WPStyleGuide.configureColors(view: view, collectionView: collectionView)
}
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
selectedAsset = nil
}
override func viewDidDisappear(_ animated: Bool) {
super.viewDidDisappear(animated)
if searchBar?.isFirstResponder == true {
searchBar?.resignFirstResponder()
}
}
// MARK: - Update view state
fileprivate func updateViewState(for assetCount: Int) {
updateNavigationItemButtons(for: assetCount)
updateNoResultsView(for: assetCount)
updateSearchBar(for: assetCount)
}
private func updateNavigationItemButtons(for assetCount: Int) {
if isEditing {
navigationItem.setLeftBarButton(UIBarButtonItem(barButtonSystemItem: .cancel, target: self, action: #selector(editTapped)), animated: false)
let trashButton = UIBarButtonItem(image: .gridicon(.trash), style: .plain, target: self, action: #selector(trashTapped))
trashButton.accessibilityLabel = NSLocalizedString("Trash", comment: "Accessibility label for trash button to delete items from the user's media library")
trashButton.accessibilityHint = NSLocalizedString("Trash selected media", comment: "Accessibility hint for trash button to delete items from the user's media library")
navigationItem.setRightBarButtonItems([trashButton], animated: true)
navigationItem.rightBarButtonItem?.isEnabled = false
} else {
navigationItem.setLeftBarButton(nil, animated: false)
var barButtonItems = [UIBarButtonItem]()
if blog.userCanUploadMedia && assetCount > 0 {
let addButton = UIBarButtonItem(barButtonSystemItem: .add, target: self, action: #selector(addTapped))
addButton.accessibilityLabel = NSLocalizedString("Add", comment: "Accessibility label for add button to add items to the user's media library")
addButton.accessibilityHint = NSLocalizedString("Add new media", comment: "Accessibility hint for add button to add items to the user's media library")
barButtonItems.append(addButton)
}
if blog.supports(.mediaDeletion) && assetCount > 0 {
let editButton = UIBarButtonItem(barButtonSystemItem: .edit, target: self, action: #selector(editTapped))
editButton.accessibilityLabel = NSLocalizedString("Edit", comment: "Accessibility label for edit button to enable multi selection mode in the user's media library")
editButton.accessibilityHint = NSLocalizedString("Enter edit mode to enable multi select to delete", comment: "Accessibility hint for edit button to enable multi selection mode in the user's media library")
barButtonItems.append(editButton)
navigationItem.setRightBarButtonItems(barButtonItems, animated: false)
} else {
navigationItem.setRightBarButtonItems(barButtonItems, animated: false)
}
}
}
fileprivate func updateNoResultsView(for assetCount: Int) {
guard assetCount == 0 else { return }
if isLoading {
noResultsView.configureForFetching()
} else {
noResultsView.removeFromView()
if hasSearchQuery {
noResultsView.configureForNoSearchResult()
} else {
noResultsView.configureForNoAssets(userCanUploadMedia: blog.userCanUploadMedia)
}
}
}
private func updateSearchBar(for assetCount: Int) {
let shouldShowBar = hasSearchQuery || assetCount > 0
if shouldShowBar {
showSearchBar()
if let searchBar = self.searchBar {
WPStyleGuide.configureSearchBar(searchBar)
}
} else {
hideSearchBar()
}
}
private func reloadCell(for media: Media) {
visibleCells(for: media).forEach { cell in
cell.overlayView = nil
cell.asset = media
}
}
private func updateCellProgress(_ progress: Double, for media: Media) {
visibleCells(for: media).forEach { cell in
if let overlayView = cell.overlayView as? CircularProgressView {
if progress < MediaLibraryViewController.uploadCompleteProgress {
overlayView.state = .progress(progress)
} else {
overlayView.state = .indeterminate
}
configureAppearance(for: overlayView, with: media)
}
}
}
private func configureAppearance(for overlayView: CircularProgressView, with media: Media) {
if media.localThumbnailURL != nil {
overlayView.backgroundColor = overlayView.backgroundColor?.withAlphaComponent(0.5)
} else {
overlayView.backgroundColor = overlayView.backgroundColor?.withAlphaComponent(1)
}
}
private func showUploadingStateForCell(for media: Media) {
visibleCells(for: media).forEach { cell in
if let overlayView = cell.overlayView as? CircularProgressView {
overlayView.state = .indeterminate
}
}
}
private func showFailedStateForCell(for media: Media) {
visibleCells(for: media).forEach { cell in
if let overlayView = cell.overlayView as? CircularProgressView {
overlayView.state = .retry
configureAppearance(for: overlayView, with: media)
}
}
}
private func visibleCells(for media: Media) -> [WPMediaCollectionViewCell] {
guard let cells = collectionView?.visibleCells as? [WPMediaCollectionViewCell] else {
return []
}
return cells.filter({ ($0.asset as? Media) == media })
}
private var hasSearchQuery: Bool {
return (pickerDataSource.searchQuery ?? "").count > 0
}
// MARK: - Actions
@objc fileprivate func addTapped() {
showOptionsMenu()
}
private func showOptionsMenu() {
let pickingContext: MediaPickingContext
if pickerDataSource.totalAssetCount > 0 {
pickingContext = MediaPickingContext(origin: self, view: view, barButtonItem: navigationItem.rightBarButtonItem, blog: blog)
} else {
pickingContext = MediaPickingContext(origin: self, view: noResultsView.actionButton, blog: blog)
}
mediaPickingCoordinator.present(context: pickingContext)
}
@objc private func editTapped() {
isEditing = !isEditing
}
@objc private func trashTapped() {
let message: String
if selectedAssets.count == 1 {
message = NSLocalizedString("Are you sure you want to permanently delete this item?", comment: "Message prompting the user to confirm that they want to permanently delete a media item. Should match Calypso.")
} else {
message = NSLocalizedString("Are you sure you want to permanently delete these items?", comment: "Message prompting the user to confirm that they want to permanently delete a group of media items.")
}
let alertController = UIAlertController(title: nil,
message: message,
preferredStyle: .alert)
alertController.addCancelActionWithTitle(NSLocalizedString("Cancel", comment: "Verb. Button title. Tapping cancels an action."))
alertController.addDestructiveActionWithTitle(NSLocalizedString("Delete", comment: "Title for button that permanently deletes one or more media items (photos / videos)"), handler: { action in
self.deleteSelectedItems()
})
present(alertController, animated: true)
}
private func deleteSelectedItems() {
guard selectedAssets.count > 0 else { return }
guard let assets = selectedAssets as? [Media] else { return }
let deletedItemsCount = assets.count
let updateProgress = { (progress: Progress?) in
let fractionCompleted = progress?.fractionCompleted ?? 0
SVProgressHUD.showProgress(Float(fractionCompleted), status: NSLocalizedString("Deleting...", comment: "Text displayed in HUD while a media item is being deleted."))
}
SVProgressHUD.setDefaultMaskType(.clear)
SVProgressHUD.setMinimumDismissTimeInterval(1.0)
// Initialize the progress HUD before we start
updateProgress(nil)
isEditing = false
MediaCoordinator.shared.delete(media: assets,
onProgress: updateProgress,
success: { [weak self] in
WPAppAnalytics.track(.mediaLibraryDeletedItems, withProperties: ["number_of_items_deleted": deletedItemsCount], with: self?.blog)
SVProgressHUD.showSuccess(withStatus: NSLocalizedString("Deleted!", comment: "Text displayed in HUD after successfully deleting a media item"))
},
failure: {
SVProgressHUD.showError(withStatus: NSLocalizedString("Unable to delete all media items.", comment: "Text displayed in HUD if there was an error attempting to delete a group of media items."))
})
}
fileprivate func presentRetryOptions(for media: Media) {
let style: UIAlertController.Style = UIDevice.isPad() ? .alert : .actionSheet
let alertController = UIAlertController(title: nil, message: nil, preferredStyle: style)
alertController.addDestructiveActionWithTitle(NSLocalizedString("Cancel Upload", comment: "Media Library option to cancel an in-progress or failed upload.")) { _ in
MediaCoordinator.shared.delete(media: [media])
}
if media.remoteStatus == .failed {
if let error = media.error {
alertController.message = error.localizedDescription
}
if media.absoluteLocalURL != nil {
alertController.addDefaultActionWithTitle(NSLocalizedString("Retry Upload", comment: "User action to retry media upload.")) { _ in
let info = MediaAnalyticsInfo(origin: .mediaLibrary(.wpMediaLibrary))
MediaCoordinator.shared.retryMedia(media, analyticsInfo: info)
}
} else {
alertController.addDefaultActionWithTitle(NSLocalizedString("Delete", comment: "User action to delete media.")) { _ in
MediaCoordinator.shared.delete(media: [media])
}
}
}
alertController.addCancelActionWithTitle(NSLocalizedString("Dismiss", comment: "Verb. Button title. Tapping dismisses a prmopt."))
present(alertController, animated: true)
}
override var isEditing: Bool {
didSet {
updateNavigationItemButtons(for: pickerDataSource.totalAssetCount)
let options = self.options.copy() as! WPMediaPickerOptions
options.allowMultipleSelection = isEditing
self.options = options
clearSelectedAssets(false)
}
}
// MARK: - Media Library Change Observer
private var mediaLibraryChangeObserverKey: NSObjectProtocol? = nil
private func registerChangeObserver() {
assert(mediaLibraryChangeObserverKey == nil)
mediaLibraryChangeObserverKey = pickerDataSource.registerChangeObserverBlock({ [weak self] _, removed, inserted, _, _ in
guard let strongSelf = self else { return }
guard removed.count > 0 || inserted.count > 0 else { return }
strongSelf.updateViewState(for: strongSelf.pickerDataSource.numberOfAssets())
if strongSelf.pickerDataSource.totalAssetCount > 0 {
strongSelf.updateNavigationItemButtonsForCurrentAssetSelection()
} else {
strongSelf.isEditing = false
}
// If we're presenting an item and it's been deleted, pop the
// detail view off the stack
if let navigationController = strongSelf.navigationController,
navigationController.topViewController != strongSelf,
let asset = strongSelf.selectedAsset,
asset.isDeleted {
_ = strongSelf.navigationController?.popToViewController(strongSelf, animated: true)
}
})
}
private func unregisterChangeObserver() {
if let mediaLibraryChangeObserverKey = mediaLibraryChangeObserverKey {
pickerDataSource.unregisterChangeObserver(mediaLibraryChangeObserverKey)
}
}
// MARK: - Upload Coordinator Observer
private func registerUploadCoordinatorObserver() {
uploadObserverUUID = MediaCoordinator.shared.addObserver({ [weak self] (media, state) in
switch state {
case .progress(let progress):
if media.remoteStatus == .failed {
self?.showFailedStateForCell(for: media)
} else {
self?.updateCellProgress(progress, for: media)
}
case .processing, .uploading:
self?.showUploadingStateForCell(for: media)
case .ended:
self?.reloadCell(for: media)
case .failed:
self?.showFailedStateForCell(for: media)
case .thumbnailReady:
if media.remoteStatus == .failed {
self?.showFailedStateForCell(for: media)
} else {
self?.showUploadingStateForCell(for: media)
}
}
}, for: nil)
}
private func unregisterUploadCoordinatorObserver() {
if let uuid = uploadObserverUUID {
MediaCoordinator.shared.removeObserver(withUUID: uuid)
}
}
}
// MARK: - UIDocumentPickerDelegate
extension MediaLibraryViewController: UIDocumentPickerDelegate {
func documentPicker(_ controller: UIDocumentPickerViewController, didPickDocumentsAt urls: [URL]) {
for documentURL in urls as [NSURL] {
let info = MediaAnalyticsInfo(origin: .mediaLibrary(.otherApps), selectionMethod: .documentPicker)
MediaCoordinator.shared.addMedia(from: documentURL, to: blog, analyticsInfo: info)
}
}
func documentPickerWasCancelled(_ controller: UIDocumentPickerViewController) {
dismiss(animated: true)
}
}
// MARK: - NoResultsViewControllerDelegate
extension MediaLibraryViewController: NoResultsViewControllerDelegate {
func actionButtonPressed() {
addTapped()
}
}
// MARK: - User messages for video limits allowances
extension MediaLibraryViewController: VideoLimitsAlertPresenter {}
// MARK: - WPMediaPickerViewControllerDelegate
extension MediaLibraryViewController: WPMediaPickerViewControllerDelegate {
func emptyViewController(forMediaPickerController picker: WPMediaPickerViewController) -> UIViewController? {
return noResultsView
}
func mediaPickerController(_ picker: WPMediaPickerViewController, didUpdateSearchWithAssetCount assetCount: Int) {
updateNoResultsView(for: assetCount)
}
func mediaPickerController(_ picker: WPMediaPickerViewController, didFinishPicking assets: [WPMediaAsset]) {
// We're only interested in the upload picker
guard picker != self else { return }
pickerDataSource.searchCancelled()
dismiss(animated: true)
guard ReachabilityUtils.isInternetReachable() else {
ReachabilityUtils.showAlertNoInternetConnection()
return
}
guard let assets = assets as? [PHAsset],
assets.count > 0 else { return }
for asset in assets {
let info = MediaAnalyticsInfo(origin: .mediaLibrary(.deviceLibrary), selectionMethod: .fullScreenPicker)
MediaCoordinator.shared.addMedia(from: asset, to: blog, analyticsInfo: info)
}
}
func mediaPickerControllerDidCancel(_ picker: WPMediaPickerViewController) {
pickerDataSource.searchCancelled()
dismiss(animated: true)
}
func mediaPickerController(_ picker: WPMediaPickerViewController, willShowOverlayView overlayView: UIView, forCellFor asset: WPMediaAsset) {
guard let overlayView = overlayView as? CircularProgressView,
let media = asset as? Media else {
return
}
WPStyleGuide.styleProgressViewForMediaCell(overlayView)
switch media.remoteStatus {
case .processing:
if let progress = MediaCoordinator.shared.progress(for: media) {
overlayView.state = .progress(progress.fractionCompleted)
} else {
overlayView.state = .indeterminate
}
case .pushing:
if let progress = MediaCoordinator.shared.progress(for: media) {
overlayView.state = .progress(progress.fractionCompleted)
}
case .failed:
overlayView.state = .retry
default: break
}
configureAppearance(for: overlayView, with: media)
}
func mediaPickerController(_ picker: WPMediaPickerViewController, shouldShowOverlayViewForCellFor asset: WPMediaAsset) -> Bool {
if picker != self, !blog.canUploadAsset(asset) {
return true
}
if let media = asset as? Media {
return media.remoteStatus != .sync
}
return false
}
func mediaPickerControllerShouldShowCustomHeaderView(_ picker: WPMediaPickerViewController) -> Bool {
guard #available(iOS 14.0, *),
FeatureFlag.mediaPickerPermissionsNotice.enabled,
picker != self else {
return false
}
// Show the device media permissions header if photo library access is limited
return PHPhotoLibrary.authorizationStatus(for: .readWrite) == .limited
}
func mediaPickerControllerReferenceSize(forCustomHeaderView picker: WPMediaPickerViewController) -> CGSize {
guard #available(iOS 14.0, *) else {
return .zero
}
let header = DeviceMediaPermissionsHeader()
header.translatesAutoresizingMaskIntoConstraints = false
return header.referenceSizeInView(picker.view)
}
func mediaPickerController(_ picker: WPMediaPickerViewController, configureCustomHeaderView headerView: UICollectionReusableView) {
guard #available(iOS 14.0, *),
let headerView = headerView as? DeviceMediaPermissionsHeader else {
return
}
headerView.presenter = picker
}
func mediaPickerController(_ picker: WPMediaPickerViewController, previewViewControllerFor asset: WPMediaAsset) -> UIViewController? {
guard picker == self else { return WPAssetViewController(asset: asset) }
guard let media = asset as? Media,
media.remoteStatus == .sync else {
return nil
}
WPAppAnalytics.track(.mediaLibraryPreviewedItem, with: blog)
return mediaItemViewController(for: asset)
}
func mediaPickerController(_ picker: WPMediaPickerViewController, shouldSelect asset: WPMediaAsset) -> Bool {
if picker != self, !blog.canUploadAsset(asset) {
presentVideoLimitExceededFromPicker(on: picker)
return false
}
guard picker == self else {
return true
}
guard let media = asset as? Media else {
return false
}
guard !isEditing else {
return media.remoteStatus == .sync || media.remoteStatus == .failed
}
switch media.remoteStatus {
case .failed, .pushing, .processing:
presentRetryOptions(for: media)
case .sync:
if let viewController = mediaItemViewController(for: asset) {
WPAppAnalytics.track(.mediaLibraryPreviewedItem, with: blog)
navigationController?.pushViewController(viewController, animated: true)
}
default: break
}
return false
}
func mediaPickerController(_ picker: WPMediaPickerViewController, didSelect asset: WPMediaAsset) {
guard picker == self else { return }
updateNavigationItemButtonsForCurrentAssetSelection()
}
func mediaPickerController(_ picker: WPMediaPickerViewController, didDeselect asset: WPMediaAsset) {
guard picker == self else { return }
updateNavigationItemButtonsForCurrentAssetSelection()
}
@objc func updateNavigationItemButtonsForCurrentAssetSelection() {
if isEditing {
// Check that our selected items haven't been deleted – we're notified
// of changes to the data source before the collection view has
// updated its selected assets.
guard let assets = (selectedAssets as? [Media]) else { return }
let existingAssets = assets.filter({ !$0.isDeleted })
navigationItem.rightBarButtonItem?.isEnabled = (existingAssets.count > 0)
}
}
private func mediaItemViewController(for asset: WPMediaAsset) -> UIViewController? {
if isEditing { return nil }
guard let asset = asset as? Media else {
return nil
}
selectedAsset = asset
return MediaItemViewController(media: asset)
}
func mediaPickerControllerWillBeginLoadingData(_ picker: WPMediaPickerViewController) {
guard picker == self else { return }
isLoading = true
updateNoResultsView(for: pickerDataSource.numberOfAssets())
}
func mediaPickerControllerDidEndLoadingData(_ picker: WPMediaPickerViewController) {
guard picker == self else { return }
isLoading = false
updateViewState(for: pickerDataSource.numberOfAssets())
}
func mediaPickerController(_ picker: WPMediaPickerViewController, handleError error: Error) -> Bool {
guard picker == self else { return false }
let nserror = error as NSError
if let mediaLibrary = self.blog.media, !mediaLibrary.isEmpty {
let title = NSLocalizedString("Unable to Sync", comment: "Title of error prompt shown when a sync the user initiated fails.")
WPError.showNetworkingNotice(title: title, error: nserror)
}
return true
}
}
// MARK: - State restoration
extension MediaLibraryViewController: UIViewControllerRestoration {
enum EncodingKey {
static let blogURL = "blogURL"
}
static func viewController(withRestorationIdentifierPath identifierComponents: [String],
coder: NSCoder) -> UIViewController? {
guard let identifier = identifierComponents.last,
identifier == MediaLibraryViewController.restorationIdentifier else {
return nil
}
guard let blogURL = coder.decodeObject(forKey: EncodingKey.blogURL) as? URL else {
return nil
}
let context = ContextManager.sharedInstance().mainContext
guard let objectID = context.persistentStoreCoordinator?.managedObjectID(forURIRepresentation: blogURL),
let object = try? context.existingObject(with: objectID),
let blog = object as? Blog else {
return nil
}
return MediaLibraryViewController(blog: blog)
}
override func encodeRestorableState(with coder: NSCoder) {
super.encodeRestorableState(with: coder)
coder.encode(blog.objectID.uriRepresentation(), forKey: EncodingKey.blogURL)
}
}
fileprivate extension Blog {
var userCanUploadMedia: Bool {
// Self-hosted non-Jetpack blogs have no capabilities, so we'll just assume that users can post media
return capabilities != nil ? isUploadingFilesAllowed() : true
}
}
// MARK: Stock Photos Picker Delegate
extension MediaLibraryViewController: StockPhotosPickerDelegate {
func stockPhotosPicker(_ picker: StockPhotosPicker, didFinishPicking assets: [StockPhotosMedia]) {
guard assets.count > 0 else {
return
}
let mediaCoordinator = MediaCoordinator.shared
assets.forEach { stockPhoto in
let info = MediaAnalyticsInfo(origin: .mediaLibrary(.stockPhotos), selectionMethod: .fullScreenPicker)
mediaCoordinator.addMedia(from: stockPhoto, to: blog, analyticsInfo: info)
WPAnalytics.track(.stockMediaUploaded)
}
}
}
// MARK: Tenor Picker Delegate
extension MediaLibraryViewController: TenorPickerDelegate {
func tenorPicker(_ picker: TenorPicker, didFinishPicking assets: [TenorMedia]) {
guard assets.count > 0 else {
return
}
let mediaCoordinator = MediaCoordinator.shared
assets.forEach { tenorMedia in
let info = MediaAnalyticsInfo(origin: .mediaLibrary(.tenor), selectionMethod: .fullScreenPicker)
mediaCoordinator.addMedia(from: tenorMedia, to: blog, analyticsInfo: info)
WPAnalytics.track(.tenorUploaded)
}
}
}