1

I'm trying to import mp3 files into my app from outside the app's sandbox using the file browser. I have a "store" environment object where i have the folder URL to which I'd like to move the selected file. I want to add that store as an environment object to the file picker.

Here's how I call the document picker from a view (here's just the relevant code):

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)
                })
}}

And here's the document picker code:

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)
        }
    }
}

Here's the store code:

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)
        }
    }

So I want to import the file to my app's sandbox within the documentPicker function, like in the commented code. But I can't add an environment object to the view controller. I don't know whether it's possible at all to do it because I'm using the root view controller to show the document picker.

0 Answers0