I need to use print() within a static function in Swift. The function needs to be called using an observer pattern as seen below:
import Foundation
@NSApplicationMain
class Application: NSObject, NSApplicationDelegate {
static var commandArgsObserver: NSKeyValueObservation?
override init() {
Application.setObserver()
...
}
static func setObserver()
commandArgsObserver = storedSettings.observe(.commandArgs, options: [.initial, .new], changeHandler: { (defaults, change) in
if let newArgs = change.newValue {
if newArgs != nil {
handleNewCommandLineArguments(arguments: newArgs!)
...
}
}
})
}
static func handleNewCommandLineArguments(arguments: [String]) {
print("I do not see this... :(")
...
}
}
I can confirm that print() works from init(). Code immediately following print() is also being executed. I’m thinking the print function doesn’t properly get the "right" standard output?
For additional context, this GUI application starts as a launch agent and runs continuously in the system menu. What I’m trying to do now is print text when a second instance of the app is run via Terminal line with the -help parameter.
Thanks for any help with this! I’m not particularly familiar with macOS/Swift and have more experience with Windows/C#
2
Answers
I found the issue and feel a little dumb. The second instance of the app was just passing command line parameters to the first instance (using the observer) and quitting. The print function was being run by the first instance (not the one running in Terminal).
To fix this, I have to print text before the second instance of the app quits so that stdout is pointed to Terminal (duh).
Sorry if I wasted anyone's time!
The
print
function only logs to the debugger, you need to use eitherNSLog
orOSLog
NSLog:
OSLog: