Versione Swift 3, basata sul codice di Rintaro e sulla soluzione di Cenox Kang.
Vedi la risposta di Rintaro per le istruzioni.
rilancio/main.swift:
import AppKit
// KVO helper
class Observer: NSObject {
let _callback:() -> Void
init(callback: @escaping() -> Void) {
_callback = callback
}
override func observeValue(forKeyPath keyPath: String?,
of object: Any?,
change: [NSKeyValueChangeKey : Any]?,
context: UnsafeMutableRawPointer?) {
_callback()
}
}
// main
autoreleasepool {
// the application pid
guard let parentPID = Int32(CommandLine.arguments[1]) else {
fatalError("Relaunch: parentPID == nil.")
}
// get the application instance
if let app = NSRunningApplication(processIdentifier: parentPID) {
// application URL
let bundleURL = app.bundleURL!
// terminate() and wait terminated.
let listener = Observer { CFRunLoopStop(CFRunLoopGetCurrent()) }
app.addObserver(listener, forKeyPath: "isTerminated", context: nil)
app.terminate()
CFRunLoopRun() // wait KVO notification
app.removeObserver(listener, forKeyPath: "isTerminated", context: nil)
// relaunch
do {
try NSWorkspace.shared().launchApplication(at: bundleURL, configuration: [:])
} catch {
fatalError("Relaunch: NSWorkspace.shared().launchApplication failed.")
}
}
}
NSApplication + Relaunch.swift:
import AppKit
extension NSApplication {
func relaunch(sender: AnyObject?) {
let task = Process()
// helper tool path
task.launchPath = Bundle.main.path(forResource: "relaunch", ofType: nil)!
// self PID as a argument
task.arguments = [String(ProcessInfo.processInfo.processIdentifier)]
task.launch()
}
}
fonte
2016-09-20 10:37:29
Si potrebbe trovare th it usa il wrapper Swift per le funzioni POSIX [exec *] (http://pubs.opengroup.org/onlinepubs/9699919799/functions/exec.html) –