Reputation: 1095
I have folder with files in my app. How can i open default Files app with myapp folder programmatically?
This is similar folder of GarageBand App in Files.
Upvotes: 10
Views: 6299
Reputation: 8224
TLDR; documentPicker.directoryURL = <#your folder directory#>
You need to use a UIViewControllerRepresentable
and a Coordinator
Class. The Class can be nested inside your Struct. The present it where required with a .sheet()
import Foundation
import SwiftUI
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
// .... your action ......
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: [<#UTTypes#>], asCopy: true)
documentPicker.directoryURL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first! //<-- This opens Files App to your Apps Documents Folder
documentPicker.delegate = context.coordinator
return documentPicker
}
func updateUIViewController(_ uiViewController: UIDocumentPickerViewController, context: Context) {
//can be left empty but the function must exists
}
}
Upvotes: 1
Reputation: 2551
You can open Files
app in specific folder using shareddocuments:
URL scheme and providing file path.
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)
For more information, read this article.
Upvotes: 19