MacOS App添加开机自启动

GitHub

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

2.png

3.png
4.png

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

5.png

设置这个target的info和Build Setting


6.png
7.png

开启沙盒

8.png

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

9.png

设置Build Setting

10.png

开启沙盒

11.png

二、添加代码

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

    @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添加代码

    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运行一下,就可以了。

©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 135,856评论 19 139
  • Spring Boot 参考指南 介绍 转载自:https://www.gitbook.com/book/qbgb...
    毛宇鹏阅读 47,126评论 6 342
  • 这几天可能因为身体状态,情绪有点糟糕。停更了两天,心中无净土,也写不出什么字句。 这两天又陆陆续续...
    菩提释阅读 1,328评论 0 1
  • 【人的转变哪里是一瞬间完成的,时间的磨蚀,痛感的流逝,日积月累,等到了一定过程,他忽然明白,再也不能这样过下去了,...
    糖糖CandyL阅读 2,839评论 0 1
  • 或许多年以后的今天我仍然会怀念那些午后的日子。知了在树上不停地呐喊,葡萄架上的叶子舒展着身体和阳光玩着影子游戏,那...
    sherly茜阅读 1,684评论 0 0

友情链接更多精彩内容