FolderPicker.swift 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. //
  2. // FolderPicker.swift
  3. // App
  4. //
  5. // Created by weihua on 9/29/21.
  6. //
  7. import Capacitor
  8. import Foundation
  9. import MobileCoreServices
  10. @objc(FolderPicker)
  11. public class FolderPicker: CAPPlugin, UIDocumentPickerDelegate {
  12. public var _call: CAPPluginCall?
  13. @objc func pickFolder(_ call: CAPPluginCall) {
  14. self._call = call
  15. DispatchQueue.main.async { [weak self] in
  16. let documentPicker = UIDocumentPickerViewController(
  17. documentTypes: [String(kUTTypeFolder)],
  18. in: UIDocumentPickerMode.open
  19. )
  20. // Set the initial directory.
  21. if let path = call.getString("path") {
  22. guard let url = URL(string: path) else {
  23. call.reject("can not parse url")
  24. return
  25. }
  26. print("picked folder url = " + url.path)
  27. documentPicker.directoryURL = url
  28. }
  29. documentPicker.allowsMultipleSelection = false
  30. documentPicker.delegate = self
  31. documentPicker.modalPresentationStyle = UIModalPresentationStyle.fullScreen
  32. self?.bridge?.viewController?.present(
  33. documentPicker,
  34. animated: true,
  35. completion: nil
  36. )
  37. }
  38. }
  39. public func documentPicker(
  40. _ controller: UIDocumentPickerViewController,
  41. didPickDocumentsAt urls: [URL]
  42. ) {
  43. var items: [String] = []
  44. let documentsPath = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)
  45. for url in urls {
  46. items.append(url.absoluteString)
  47. }
  48. self._call?.resolve([
  49. "path": items.first as Any,
  50. "localDocumentsPath": documentsPath[0] as Any
  51. ])
  52. }
  53. }