index.uts 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  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. try {
  20. const res = {
  21. code: "0",
  22. filePath:urls[0].absoluteString,
  23. fileName: fileName,
  24. errMsg: 'fileselect:ok',
  25. detail: "文件读取成功"
  26. }
  27. if (this.infoOptions != null) {
  28. this.infoOptions?.success?.(res)
  29. this.infoOptions?.complete?.(res)
  30. }
  31. }catch (e) {
  32. console.log(e.message)
  33. const res_fail = {
  34. code: "1002",
  35. errMsg: 'fileselect:fail',
  36. detail: "文件不存在"
  37. }
  38. this.infoOptions?.fail?.(res_fail)
  39. this.infoOptions?.complete?.(res_fail)
  40. }
  41. }
  42. documentPickerWasCancelled(controller : UIDocumentPickerViewController) {
  43. const res = {
  44. code: "1004",
  45. errMsg: 'fileselect:fail',
  46. detail: "用户取消了选择"
  47. }
  48. this.infoOptions?.fail?.(res)
  49. this.infoOptions?.complete?.(res)
  50. }
  51. fileSelect(options : InfoOptions) {
  52. this.infoOptions = options
  53. DispatchQueue.main.async(execute = () : void => {
  54. const types = ["public.data"]
  55. if (this.docPicker == null) {
  56. this.docPicker = new UIDocumentPickerViewController(documentTypes = types, in = UIDocumentPickerMode.import)
  57. this.docPicker.delegate = this
  58. }
  59. UTSiOS.getCurrentViewController().present(this.docPicker, animated = true)
  60. })
  61. }
  62. }
  63. const docPicker : DocumentPicker = new DocumentPicker();
  64. export default function fileSelect(options : InfoOptions) {
  65. docPicker.fileSelect(options)
  66. }