ImageFetcher.swift 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. //
  2. // ALImageFetchingInteractor.swift
  3. // ALImagePickerViewController
  4. //
  5. // Created by Alex Littlejohn on 2015/06/09.
  6. // Copyright (c) 2015 zero. All rights reserved.
  7. //
  8. import UIKit
  9. import Photos
  10. public typealias ImageFetcherSuccess = (PHFetchResult<PHAsset>) -> ()
  11. public typealias ImageFetcherFailure = (NSError) -> ()
  12. //extension PHFetchResult: Sequence {
  13. // public func makeIterator() -> NSFastEnumerationIterator {
  14. // return NSFastEnumerationIterator(self)
  15. // }
  16. //}
  17. public class ImageFetcher {
  18. private var success: ImageFetcherSuccess?
  19. private var failure: ImageFetcherFailure?
  20. private var authRequested = false
  21. private let errorDomain = "com.zero.imageFetcher"
  22. let libraryQueue = DispatchQueue(label: "com.zero.ALCameraViewController.LibraryQueue");
  23. public init() { }
  24. public func onSuccess(_ success: @escaping ImageFetcherSuccess) -> Self {
  25. self.success = success
  26. return self
  27. }
  28. public func onFailure(_ failure: @escaping ImageFetcherFailure) -> Self {
  29. self.failure = failure
  30. return self
  31. }
  32. public func fetch() -> Self {
  33. _ = PhotoLibraryAuthorizer { error in
  34. if error == nil {
  35. self.onAuthorized()
  36. } else {
  37. self.failure?(error!)
  38. }
  39. }
  40. return self
  41. }
  42. private func onAuthorized() {
  43. let options = PHFetchOptions()
  44. options.sortDescriptors = [NSSortDescriptor(key: "creationDate", ascending: false)]
  45. libraryQueue.async {
  46. let assets = PHAsset.fetchAssets(with: PHAssetMediaType.image, options: options)
  47. DispatchQueue.main.async {
  48. self.success?(assets)
  49. }
  50. }
  51. }
  52. }