【问题标题】:How to create a button that can exit the application and restart the system when clicked in a Cocoa Application?如何在可可应用程序中创建一个可以退出应用程序并在单击时重新启动系统的按钮?
【发布时间】:2016-07-12 20:12:34
【问题描述】:

我们当前的应用程序需要重新启动系统并在单击按钮时干净地退出应用程序,但是一旦其中一个代码运行,即重新启动代码或退出应用程序的代码,其他代码将不会运行。我们的应用程序当前重新加载后重新启动,因为在系统重新启动之前它没有正确关闭。 需要重启和退出应用的按钮代码:

@IBAction func exit2(sender: AnyObject) {
        let task = NSTask()
        let pipe = NSPipe()
        task.standardOutput = pipe
       //Code to reboot the system 
        task.launchPath = "/bin/bash/"
        task.arguments = ["-c", "osascript -e 'tell app \"System Events\" to restart'"]

        let file:NSFileHandle = pipe.fileHandleForReading

        task.launch()
        task.waitUntilExit()

        let data =  file.readDataToEndOfFile()
        datastring1 = NSString(data: data, encoding: NSUTF8StringEncoding)!
        //Code to close the application
        NSApplication.sharedApplication().terminate(self)

    }

【问题讨论】:

  • 解决这个问题你面临什么问题?
  • 我们的应用程序在重新启动系统之前没有完全退出。所以它在重新启动后再次启动
  • 你应该看看this answer

标签: swift macos button exit restart


【解决方案1】:
@IBAction func restartAppButton(_ sender: Any) {
        
        if let path = Bundle.main.resourceURL?.deletingLastPathComponent().deletingLastPathComponent().absoluteString {
                NSLog("restart \(path)")
                _ = Process.launchedProcess(launchPath: "/usr/bin/open", arguments: [path])
                NSApp.terminate(self)
            }
    }

【讨论】:

  • 请添加更多详细信息以扩展您的答案,例如工作代码或文档引用。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2016-04-19
  • 2013-02-28
  • 2020-07-24
  • 2012-12-29
  • 1970-01-01
  • 1970-01-01
  • 2017-08-14
相关资源
最近更新 更多