index.uts 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. // 引用 iOS 原生平台 api
  2. import { UIDocumentPickerViewController, UIDocumentPickerMode, UIDocumentPickerDelegate, UIViewController } from "UIKit";
  3. import { DispatchQueue } from 'Dispatch';
  4. import { UTSiOS } from "DCloudUTSFoundation"
  5. import { URL ,FileManager } from 'Foundation'
  6. /**
  7. * 定义 接口参数
  8. */
  9. type InfoOptions = {
  10. success ?: (res : UTSJSONObject) => void;
  11. fail ?: (res : UTSJSONObject) => void;
  12. complete ?: (res : UTSJSONObject) => void;
  13. };
  14. class DocumentPicker extends UIViewController implements UIDocumentPickerDelegate {
  15. docPicker! : UIDocumentPickerViewController
  16. infoOptions ?: InfoOptions
  17. documentPicker(controller : UIDocumentPickerViewController, @argumentLabel("didPickDocumentsAt") urls : URL[]) {
  18. const fileName=urls[0].lastPathComponent
  19. console.warn(urls)
  20. try {
  21. const extIdx = fileName.lastIndexOf(".");
  22. const res = {
  23. code: "0",
  24. filePath:urls[0].absoluteString,
  25. fileName: fileName,
  26. errMsg: 'fileselect:ok',
  27. detail: "文件读取成功"
  28. }
  29. if (this.infoOptions != null) {
  30. this.infoOptions?.success?.(res)
  31. this.infoOptions?.complete?.(res)
  32. }
  33. }catch (e) {
  34. console.log(e.message)
  35. const res_fail = {
  36. code: "1002",
  37. errMsg: 'fileselect:fail',
  38. detail: "文件不存在"
  39. }
  40. this.infoOptions?.fail?.(res_fail)
  41. this.infoOptions?.complete?.(res_fail)
  42. }
  43. }
  44. documentPickerWasCancelled(controller : UIDocumentPickerViewController) {
  45. const res = {
  46. code: "1004",
  47. errMsg: 'fileselect:fail',
  48. detail: "用户取消了选择"
  49. }
  50. this.infoOptions?.fail?.(res)
  51. this.infoOptions?.complete?.(res)
  52. }
  53. filePicker(options : InfoOptions) {
  54. this.infoOptions = options
  55. DispatchQueue.main.async(execute = () : void => {
  56. const types = ["public.data"]
  57. if (this.docPicker == null) {
  58. this.docPicker = new UIDocumentPickerViewController(documentTypes = types, in = UIDocumentPickerMode.import)
  59. this.docPicker.delegate = this
  60. }
  61. UTSiOS.getCurrentViewController().present(this.docPicker, animated = true)
  62. })
  63. }
  64. }
  65. const docPicker : DocumentPicker = new DocumentPicker();
  66. export default function filePicker(options : InfoOptions) {
  67. docPicker.filePicker(options)
  68. }