在日常使用某些 app 時,更改語言設置後 app 會提示「軟體語言設置在重啟後會生效」,有的軟體也會提示是否立即重啟,這說明我們能實現 app 的自重啟,對吧!那麼本文將介紹如何通過代碼實現 app 的自重啟。
這裡以一個新的空工程為例,所以首先要新建一個 Cocoa App 工程。簡單說一下這個過程:
Shift
Command
N
Next
Use Storyboards
重啟的原理很簡單,就是在 app 退出前使用方法 NSWorkspace.shared.launchApplication 非同步新啟動一個 App 實例。
NSWorkspace.shared.launchApplication
為了保證重啟操作和退出的區分,需要使用一個公共變數來標記 app 是否需要重啟,如果需要重啟再進行退出前的特殊操作。將這一變數定義在 AppDelegate.swift 中,這裡注意的是要定義在 AppDelegate 類外,放在文件代碼 import Cocoa 後即可:
AppDelegate.swift
AppDelegate
import Cocoa
var toRelaunch = false
只是標記,所以定義為 Bool 類型,初始化默認值為 false。
Bool
false
app 退出前的處理可以在文件 AppDelegate.swift 的 AppDelegate 類的 applicationWillTerminate 方法中實現,實現如下:
applicationWillTerminate
if (toRelaunch) { NSWorkspace.shared.launchApplication(withBundleIdentifier: "top.smslit.RelaunchDemo", options: [NSWorkspace.LaunchOptions.async, NSWorkspace.LaunchOptions.newInstance], additionalEventParamDescriptor: nil, launchIdentifier: nil) }
這裡要注意的是 withBundleIdentifier 要更改為您的 App 相應的 Bundle Identifier ,這個可以在工程配置信息的 General 中查看。程序啟動選項使用的是:
withBundleIdentifier
Bundle Identifier
General
NSWorkspace.LaunchOptions.async
NSWorkspace.LaunchOptions.newInstance
重啟的實現就是將 toRelaunch 設置為 true 後退出 App:
toRelaunch
true
// 重啟 App func relaunchApp() { toRelaunch = true NSApplication.shared.terminate(true) }
其實,只要是在程序退出前將 toRelaunch 置為 true ,App正常退出的話就會重啟 APP。
為了看一下重啟實現的效果,可以添加一個按鈕,點擊調用剛剛實現的重啟方法 relaunchApp 就可以看到成果!
relaunchApp
打開 Main.storyboard,按下 Shift + Command + l 組合鍵就會打開控制項庫選擇器,搜索框搜索 button,找到 Push Button,點擊拖入 View Controller 的中央,這樣就完成了按鈕的添加:
Main.storyboard
l
Push Button
View Controller
下一步綁定 Action 實現點擊行為。
Option
回車
Ctrl
Insert Action or Outlet
Action
toRelaunchApp
具體操作參考下面視頻:
點擊 Xcode 左上角的運行按鈕或按下組合鍵 Command + r 就會啟動 App,在出現的窗口中就會看到我們添加的按鈕,點擊它就會發現 App 進行了重啟,大功告成!
r
下載此 Demo:
Cocoa 怎樣重新啟動app (application relaunching)?blog.csdn.netNSWorkspace | Apple Developer Documentation?developer.apple.com
博客原文: