1

我正在尝试使用文件浏览器从应用程序的沙箱外部将 mp3 文件导入我的应用程序。我有一个“存储”环境对象,其中有我想将所选文件移动到的文件夹 URL。我想将该商店作为环境对象添加到文件选择器中。

这是我从视图中调用文档选择器的方式(这里只是相关代码):

struct libraryView: View {

  @State var filePicker : DocumentPicker
  @EnvironmentObject var store : MusicStore
  @State var showPicker = false
    

  func presentDocumentPicker() {
            let viewController = UIApplication.shared.windows[0].rootViewController!
            let controller = filePicker.viewController
            viewController.present(controller, animated: true)    
        }

  var body: some View {
    Button(action: {showPicker = true
                    presentDocumentPicker()
                }, label: {
                    Image(systemName: "plus").imageScale(.large)
                })
}}

这是文档选择器代码:

final class DocumentPicker: NSObject, ObservableObject {
    @EnvironmentObject var store : MusicStore

     lazy var viewController: UIDocumentPickerViewController = {
        let vc = UIDocumentPickerViewController(documentTypes: types, in: .import)
        vc.delegate = self
        vc.allowsMultipleSelection = self.allowsMultipleSelection
        return vc
    }()
}

extension DocumentPicker: UIDocumentPickerDelegate {
  func documentPicker(_ controller: UIDocumentPickerViewController, didPickDocumentsAt urls: [URL]) {
        callback(urls)
    do {
        let filePath = try FileManager.default.contentsOfDirectory(at: url.deletingLastPathComponent(), includingPropertiesForKeys: nil, options: [])[0]
        let audioFile = try Data(contentsOf: filePath)
//      let destinationURL = store.folderURL!.appendingPathComponent(filePath.lastPathComponent)
//      try FileManager.default.moveItem(at: filePath, to: destinationURL)
//      print("File moved to documents folder")
        }
     catch {
        print(error)
        }
    }
}

这是商店代码:

class MusicStore : ObservableObject {
  var folderURL : URL?
  init(){
        do{
            self.folderURL = try FileManager.default.url(
                for: .documentDirectory,
                in: .userDomainMask,
                appropriateFor: nil,
                create: false
            )} catch(let error) {
               print(error.localizedDescription)
        }
    }

所以我想在 documentPicker 函数中将文件导入到我的应用程序的沙箱中,就像在注释代码中一样。但我无法将环境对象添加到视图控制器。我不知道是否可以这样做,因为我正在使用根视图控制器来显示文档选择器。

4

0 回答 0