MacOS App添加开机自启动

不说废话bash

1、在项目的targets下再添加一个target

而后删除添加的target中Main.storyboard中的Main Menu和Window.app

设置这个target的info和Build Settingui

开启沙盒

在项目的target中的Build Phases中添加CopyFile到Contents/Library/LoginItemsspa

设置Build Setting3d

开启沙盒code

2、添加代码

在AppDelegate或有设置按钮的地方添加代码cdn

@IBAction func appWhenLoginAction(_ sender: NSButton) {
        let state = sender.state
        
        if state == .on {
            self.startupAppWhenLogin(startup: true)
        } else {
            self.startupAppWhenLogin(startup: false)
        }
    }
    
    func startupAppWhenLogin(startup: Bool) {
        // 这里请填写你本身的Heler BundleID
        let launcherAppIdentifier = "liwei.LwWallpapersHelper"
        
        // 开始注册/取消启动项
        if SMLoginItemSetEnabled(launcherAppIdentifier as CFString, startup) {
            if startup {
                NSLog("添加登陆项成功.")
            } else {
                NSLog("移除登陆项成功.")
            }
        } else {
            NSLog("添加失败.")
        }
        
    
        
    }
复制代码

在添加的target的AppDelegate添加代码blog

func applicationDidFinishLaunching(_ aNotification: Notification) {
        var compoents = (Bundle.main.bundlePath as NSString).pathComponents as NSArray
        compoents = compoents.subarray(with: NSMakeRange(0, compoents.count - 4)) as NSArray
        let path = NSString.path(withComponents: compoents as! [String])
        NSWorkspace.shared.launchApplication(path)
        terminate()
    }
    
    @objc func terminate() {
        NSApp.terminate(nil)
    }
复制代码

而后导出APP运行一下,就能够了。get

相关文章
相关标签/搜索