I am writing a Mac app in SwiftUI and would like to display a live-updated list of documents and folders with the ability to edit the files.
First, users selects any folder with Open File Dialog and then I save the URL into UserDefaults and attempt to read list of files and folders when the app launches.
Assuming I have a valid URL then I do the following:
// Open the folder referenced by URL for monitoring only.
monitoredFolderFileDescriptor = open(url.path, O_EVTONLY)
// Define a dispatch source monitoring the folder for additions, deletions, and renamings.
folderMonitorSource = DispatchSource.makeFileSystemObjectSource(fileDescriptor: monitoredFolderFileDescriptor, eventMask: .write, queue: folderMonitorQueue)
App is crashes when I call DispatchSource.makeFileSystemObjectSource
with the EXC_BREAKPOINT exception.
FileManager.default.isReadableFile(atPath: url.path)
returns false
which tells me I don't have permissions to access this folder.
The URL path is /Users/username/Documents/Folder
I have added NSDocumentsFolderUsageDescription
into the info plist.
- It's not clear how can I ask for permission programmatically.
- Theoretically my URL can point to any folder on File systems that the user selects in the Open Dialog. It's unclear what is the best practice to request permission only when necessary. Should I parse the URL for the "Documents" or "Downloads" string?
I also have watched this WWDC video.
Thanks for reading.