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

相關文章
相關標籤/搜索