Search code examples
swiftmacoscocoansviewcontrollernsapplication-delegate

Get name of file that launched an app in ViewController class?


I implemented the NSApplicationDelegate method func application(_ sender: NSApplication, openFile filename: String) -> Bool to get the name of the file that is double-clicked to launch my macOS app (Swift 4.x). However, it appears that this method is called after ViewController viewDidLoad() which is where all my initialization code takes place. Is there a way to get the file name in viewDidLoad() in the ViewController class so that I can utilize the file name directly in my initialization code?

Update:

I am now able to pass data from AppDelegate to ViewController based on the suggestion from this link for Swift 4.2:

https://stackoverflow.com/questions/15049924/passing-data-from-app-delegate-to-view-controllerhttps://stackoverflow.com/questions/15049924/passing-data-from-app-delegate-to-view-controller

So my question remains is how to get the file name either directly in ViewDidLoad() or be able to get the name throughapplication(_, sender: NSApplication, openFile filename: String) -> Bool and have it available to be passed into the ViewController when ViewDidLoad() is called.


Solution

  • Solved my problem. Instead of performing my initialization code in ViewController, I implemented the code in AppDelegate applicationDidFinishLaunching instead so that the initialization can be performed when the app is launched and before first event occurs. I believe this is more proper practice anyway for AppDelegate to handle app initialization. This code adjustment solves both the need to pass data between ViewController and AppDelegate, as well as the issue that application(_, sender: NSApplication, openFile filename: String) -> Bool is called after ViewDidLoad().