问题描述
我想知道是否有任何方法可以通过程序重新启动我的应用程序.这是一个Mac OS应用程序,我很快就使用了Xcode 6.
I would like to know if is any method to restart my app programmatically.It's a mac os app and I work with Xcode 6 in swift.
过程很简单,在给定的时间我想重新启动我的应用程序.我想我需要一个简单的助手,但是我不确定.
The procedure is simple, at a given time I want to restart my app. I guess I need a simple Helper but i'm not sure.
推荐答案
是的,您需要帮助工具.步骤如下:
Yes, you need helper tool. here is the procedure:
-
在项目中创建帮助程序命令行工具"目标.例如,名为"重新启动"
重新启动/main.swift:
import AppKit
// KVO helper
class Observer: NSObject {
let _callback: () -> Void
init(callback: () -> Void) {
_callback = callback
}
override func observeValueForKeyPath(keyPath: String, ofObject object: AnyObject, change: [NSObject : AnyObject], context: UnsafeMutablePointer<Void>) {
_callback()
}
}
// main
autoreleasepool {
// the application pid
let parentPID = atoi(C_ARGV[1])
// 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", options: nil, context: nil)
app.terminate()
CFRunLoopRun() // wait KVO notification
app.removeObserver(listener, forKeyPath: "isTerminated", context: nil)
// relaunch
NSWorkspace.sharedWorkspace().launchApplicationAtURL(bundleURL, options: nil, configuration: [:], error: nil)
}
}
将Products/relaunch
二进制文件添加到主应用程序目标中的复制包资源".
Add Products/relaunch
binary to "Copy Bundle Resources" in the main application target.
在主应用程序目标的目标依赖项"中添加relaunch
目标.
Add relaunch
target to "Target Dependencies" in the main application target.
在主应用程序中添加relaunch
函数.
Add relaunch
function in the main application.
例如: NSApplication + Relaunch.swift :
extension NSApplication {
func relaunch(sender: AnyObject?) {
let task = NSTask()
// helper tool path
task.launchPath = NSBundle.mainBundle().pathForResource("relaunch", ofType: nil)!
// self PID as a argument
task.arguments = [String(NSProcessInfo.processInfo().processIdentifier)]
task.launch()
}
}
然后,根据需要致电NSApplication.sharedApplication().relaunch(nil)
.
这篇关于以编程方式重新启动应用程序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!