C-Viorel C-Viorel - 5 months ago 283x
Swift Question

Restart application programmaticaly

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:

  1. Create helper "Command Line Tool" target in your Project. For example, named "relaunch"


    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>) {
    // 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)
            CFRunLoopRun() // wait KVO notification
            app.removeObserver(listener, forKeyPath: "isTerminated", context: nil)
            // relaunch
            NSWorkspace.sharedWorkspace().launchApplicationAtURL(bundleURL, options: nil, configuration: [:], error: nil)
  2. Add Products/relaunch binary to "Copy Bundle Resources" in the main application target.

  3. Add relaunch target to "Target Dependencies" in the main application target.


  4. Add relaunch function in the main application.

    For example: 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)]

Then, call NSApplication.sharedApplication().relaunch(nil) as you like.