PPAssetManager.swift 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. import Photos
  2. import ImageIO
  3. import UIKit
  4. struct PPAssetManager {
  5. func getPHAssets(imagesOnly: Bool, fetchLimit: Int, _ handler: @escaping (PHFetchResult<PHAsset>?) -> ()) {
  6. guard authorizationStatus() == .authorized else {
  7. handler(nil)
  8. return
  9. }
  10. let result: PHFetchResult<PHAsset>
  11. let options = self.getFetchOptions(fetchLimit)
  12. if imagesOnly {
  13. result = PHAsset.fetchAssets(with: .image, options: options)
  14. } else {
  15. result = PHAsset.fetchAssets(with: options)
  16. }
  17. handler(result)
  18. }
  19. private func getFetchOptions(_ fetchLimit: Int) -> PHFetchOptions {
  20. let fetchOptions = PHFetchOptions()
  21. fetchOptions.fetchLimit = fetchLimit
  22. fetchOptions.includeAssetSourceTypes = .typeUserLibrary
  23. fetchOptions.predicate = NSPredicate(format: "(mediaType = %d OR mediaType = %d)", argumentArray:[PHAssetMediaType.image.rawValue, PHAssetMediaType.video.rawValue])
  24. fetchOptions.wantsIncrementalChangeDetails = false
  25. fetchOptions.includeHiddenAssets = false
  26. fetchOptions.sortDescriptors = [NSSortDescriptor(key:"creationDate", ascending: false)]
  27. return fetchOptions
  28. }
  29. private func getFetchOptions(_ offset: Int, _ count: Int) -> PHFetchOptions {
  30. let fetchOptions = PHFetchOptions()
  31. fetchOptions.fetchLimit = offset + count
  32. fetchOptions.wantsIncrementalChangeDetails = false
  33. fetchOptions.sortDescriptors = [NSSortDescriptor(key:"creationDate", ascending: false)]
  34. return fetchOptions
  35. }
  36. func requestAuthorization(_ handler: @escaping (PHAuthorizationStatus) -> Void) {
  37. PHPhotoLibrary.requestAuthorization { status in
  38. DispatchQueue.main.async {
  39. handler(status)
  40. }
  41. }
  42. }
  43. func authorizationStatus() -> PHAuthorizationStatus {
  44. return PHPhotoLibrary.authorizationStatus()
  45. }
  46. func isUnauthorizedAndCameraAvailable() -> Bool {
  47. return authorizationStatus() != .authorized && UIImagePickerController.isSourceTypeAvailable(.camera)
  48. }
  49. }