为你的MacOS App添加开机自启动(Swift)
猴子原创,欢迎转载。转载请注明: 转载自Cocos2Der-CSDN,谢谢! 关于Mac下如何给自己App添加开机自启动功能,你可以了解下Mac Developer Library中的说明。
可以看出,Apple推荐了两种方式:Service Management framework 和 shared file list。 这两种方式有差别:
下面我主要介绍的是使用Service Management framework 的方式添加开机自启动。 一、创建主工程新建一个MainApp的osx工程App 二、添加自动启动Target
三、设置配置属性
四、添加启动代码
func startupAppWhenLogin(startup: Bool) {
// 这里请填写你自己的Heler BundleID
let launcherAppIdentifier = "com.cocos2dev.MainApp.MainAppHelper"
// 开始注册/取消启动项
SMLoginItemSetEnabled(launcherAppIdentifier,startup)
var startedAtLogin = false
for app in NSWorkspace.sharedWorkspace().runningApplications {
if app.bundleIdentifier == launcherAppIdentifier {
startedAtLogin = true
}
}
if startedAtLogin { NSDistributedNotificationCenter.defaultCenter().postNotificationName("killhelper",object: NSBundle.mainBundle().bundleIdentifier!)
}
}
import Cocoa
@NSApplicationMain
class AppDelegate: NSObject,NSApplicationDelegate {
func applicationDidFinishLaunching(aNotification: NSNotification) {
// Insert code here to initialize your application
let mainAppIdentifier = "com.cocos2dev.MainApp"
let running = NSWorkspace.sharedWorkspace().runningApplications
var alreadyRunning = false
for app in running {
if app.bundleIdentifier == mainAppIdentifier {
alreadyRunning = true
break
}
}
if !alreadyRunning {
NSDistributedNotificationCenter.defaultCenter().addObserver(self,selector: "terminate",name: "killhelper",object: mainAppIdentifier)
let path = NSBundle.mainBundle().bundlePath as NSString
var components = path.pathComponents
components.removeLast()
components.removeLast()
components.removeLast()
components.append("MacOS")
components.append("MainApp") //main app name
let newPath = NSString.pathWithComponents(components)
NSWorkspace.sharedWorkspace().launchApplication(newPath)
} else {
self.terminate()
}
}
func applicationWillTerminate(aNotification: NSNotification) {
// Insert code here to tear down your application
}
func terminate() {
// NSLog("I'll be back!")
NSApp.terminate(nil)
}
}
以上就是一个自启动App的做法。当然如果你上架Mac Store,建议你不要默认就开启自启动,放到设置中,让用户自己选择开启/关闭。
(编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |