简体   繁体   English

获取在ViewController类中启动了应用程序的文件的名称?

[英]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). 我实现了NSApplicationDelegate方法func application(_ sender: NSApplication, openFile filename: String) -> Bool以获取双击启动我的macOS应用(Swift 4.x)的文件的名称。 However, it appears that this method is called after ViewController viewDidLoad() which is where all my initialization code takes place. 但是,似乎在ViewController viewDidLoad()之后调用了此方法,这是我所有初始化代码发生的地方。 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? 有没有办法在ViewController类的viewDidLoad()中获取文件名,以便我可以在初始化代码中直接使用文件名?

Update: 更新:

I am now able to pass data from AppDelegate to ViewController based on the suggestion from this link for Swift 4.2: 现在,我可以根据此链接对Swift 4.2的建议,将数据从AppDelegate传递到ViewController

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 https://stackoverflow.com/questions/15049924/passing-data-from-app-delegate-to-view-controllerhttps://stackoverflow.com/questions/15049924/passing-data-from-app-delegate-to-视图-控制器

So my question remains is how to get the file name either directly in ViewDidLoad() or be able to get the name through application(_, sender: NSApplication, openFile filename: String) -> Bool and have it available to be passed into the ViewController when ViewDidLoad() is called. 所以我的问题仍然是如何直接在ViewDidLoad()获取文件名,或者如何通过application(_, sender: NSApplication, openFile filename: String) -> Bool并将其传递给调用ViewDidLoad()时的ViewController

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. 我没有在ViewController中执行初始化代码,而是在AppDelegate applicationDidFinishLaunching实现了代码,以便可以在启动应用程序时以及在发生第一个事件之前执行初始化。 I believe this is more proper practice anyway for AppDelegate to handle app initialization. 我认为对于AppDelegate ,这是处理应用程序初始化的更合适的做法。 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() . 此代码调整解决了在ViewControllerAppDelegate之间传递数据的需要,以及解决了application(_, sender: NSApplication, openFile filename: String) -> BoolViewDidLoad()之后ViewDidLoad() application(_, sender: NSApplication, openFile filename: String) -> Bool

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM