如何以编程方式打开带有 myapp 文件夹的默认文件应用程序?

问题描述 投票:0回答:2

我的应用程序中有包含文件的文件夹。如何以编程方式使用 myapp 文件夹打开默认文件应用程序?

这与文件中 GarageBand 应用程序的文件夹类似。

ios swift directory swiftui
2个回答
15
投票

您可以使用

Files
URL 方案并提供文件路径在特定文件夹中打开
shareddocuments:
应用程序。


示例:

func getDocumentsDirectory() -> URL { // returns your application folder
    let paths = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)
    let documentsDirectory = paths[0]
    return documentsDirectory
}

let path = getDocumentsDirectory().absoluteString.replacingOccurrences(of: "file://", with: "shareddocuments://")
let url = URL(string: path)!

UIApplication.shared.open(url)


附言:

欲了解更多信息,请阅读本文


0
投票

您需要使用

UIViewControllerRepresentable
Coordinator
类。该类可以嵌套在您的结构中

Struct DocumentPicker : UIViewControllerRepresentable {

func makeCoordinator() -> Coordinator {
   Coordinator()
}

Class Coordinator : NSObject, UIDocumentPickerDelegate {
    func documentPicker(_ controller: UIDocumentPickerViewController, didPickDocumentsAt urls: [URL]) {

      //the function gives an array of urls for the selected file.
      //chances are only going to be one 
     guard let url = urls.first else { return }

    //when trying to access resources outside our apps sandbox its important to call startAccessingSecurityScopedResource(). Then stopAccessingSecurityScopedResource(). Once we have finished.

      let secureAccess = url.startAccessingSecurityScopedResource()
      //handle your file however needed for your app
      ...
      if secureAccess {
              url.stopAccessingSecurityScopedResource()
       }
      }
}

//These are required to me implemented. Though one we just can leave empty

func makeUIViewController(context: Context) -> UIDocumentPickerViewController {
        let documentPicker =  UIDocumentPickerViewController(forOpeningContentTypes: [<# in here put the UTTypes your app will handle ...,.pdf #>], asCopy: true)
        documentPicker.delegate = context.coordinator
        return documentPicker
    }
    
    func updateUIViewController(_ uiViewController: UIDocumentPickerViewController, context: Context) {
        //can be left empty but the function must exists
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.