I'm an experienced iOS developer but I'm new to developing for macOS. In this app, the user has chosen a file and I want to monitor that file for any changes so that my app can respond, read the new contents of the file, and act appropriately.
I found this article about watching for changes and have been following along, but I get a strange crash/break when I run the app. The code looks like this:
I don't get any error message in the console. No stack trace. I don't have any breakpoints set. If I comment out the source.setEventHandler
lines I still get the same crash/break. If I comment out the let source = DispatchSource.makeFileSystemObjectSource()
lines, then the code runs fine.
The url in question is a security-scoped url that was previously chosen with an NSOpenPanel() and then stored as a security-scoped bookmark.
Am I doing something wrong? I'm new to Swift 5.5 concurrency, is that causing the problem?
How can I properly watch a file for changes so that my app can automatically respond?
Text version of code for accessibility:
override func viewDidAppear() {
super.viewDidAppear()
Task {
self.configurl = await self.openfile(forkey: self.keybookmarkconfig)
if let url = self.configurl {
let configfilehandle = try FileHandle(forReadingFrom: url)
let source = DispatchSource.makeFileSystemObjectSource(
fileDescriptor: configfilehandle.fileDescriptor,
eventMask: .extend,
queue: DispatchQueue.main
)
source.setEventHandler {
print("config file changed")
}
}
}
}