您可以使用
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)
欲了解更多信息,请阅读本文。
您需要使用
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
}
}