OSX开发之守护进程(appserver)

1.状态栏程序制作

  • xcode创建项目

  • 删除Main.storyboard 中的Window和ViewController

    OSX开发之守护进程(appserver)_第1张图片
    15006520234330.jpg
  • appdelegate 添加代码

import Cocoa
@NSApplicationMain
class AppDelegate: NSObject, NSApplicationDelegate {

    let statusItem = NSStatusBar.system().statusItem(withLength: NSVariableStatusItemLength)
    var statusMenu: NSMenu!

    func applicationDidFinishLaunching(_ aNotification: Notification) {
        statusMenu = NSMenu(title: "")
        let item0 = NSMenuItem(title: "启动App", action: #selector(startApp), keyEquivalent: "")
        item0.isEnabled = true
        statusMenu.insertItem(item0, at: 0)
        
        let item1 = NSMenuItem(title: "设置", action: #selector(setting), keyEquivalent: "")
        item1.isEnabled = true
        statusMenu.insertItem(item1, at: 1)
        
        let item2 = NSMenuItem(title: "退出", action: #selector(exit), keyEquivalent: "")
        item2.isEnabled = true
        statusMenu.insertItem(item2, at: 2)
        
        let icon = NSImage(named: "icon1")
        statusItem.image = icon
        statusItem.menu = statusMenu
    }
    
    func setting() {}
    
    func exit() {
        NSApplication.shared().terminate(self)
    }
    
    func startApp()  {}
}

  • info.plist添加 Application is agent (UIElement) 为 true (隐藏dock图标)

2.主程序target添加

  • 添加target
  • Build Phases 添加copy Files选项,添加target app


    OSX开发之守护进程(appserver)_第2张图片
    15006535734128.jpg
  • 启动app
let path = Bundle.main.bundlePath.appending("/Contents/SharedSupport/MainApp.app")
let task = Process()
task.launchPath = "/usr/bin/open"
task.arguments = [path]
task.launch()

3.进程间的通讯

  • 使用CFMessagePort
  • 参考
    • iOS--CFMessagePort实现进程间通信

4.开机启启动

  • 参考

    • 三种方式配置Mac OS X的启动项
    • Creating Launch Daemons and Agents
    • 在Mac OS X下,怎样才可以在开关机时自动运行脚本程序?
    • Mac OS X启动项详解
  • 使用Launchd

    • 配置plist
    • 添加command Line Tool 并配置启动
    • copy plist文件至 /Library/LaunchAgents 目录下,copy command Line Tool 至 /Users/Shared
  • 把启动项添加到用户登录项的脚本

#把文本编辑.app 添加到用户登录项
#!/bin/bash 
/usr/bin/osascript -e "tell application \"System Events\" to make new login item with properties { path: \"/Applications/TextEdit.app\", hidden:false } at end"

github地址

你可能感兴趣的:(OSX开发之守护进程(appserver))