2017-01-09 27 views
0

我試圖在登錄時使用ServiceManagement自動啓動應用程序。主應用程序(login-Item.app)在登錄項目列表中註冊啓動器,啓動器啓動主應用程序(2個獨立的目標)。這是我有:Swift:SMLoginItemSetEnabled()在登錄時未啓動

主要應用:

func applicationDidFinishLaunching(_ notification: Notification) { 
    let helperBundleId = "abc.loginItem-launcher" 
    let ret = SMLoginItemSetEnabled(helperBundleId as CFString, true) 
    //'ret' is true at this point 

而且從發射:

func applicationDidFinishLaunching(_ aNotification: Notification) { 
    var alreadyRunning:Bool = false 
    for app in NSWorkspace.shared().runningApplications{ 
     if app.bundleIdentifier == "abc.login-item"{ 
      alreadyRunning = true 
      break; 
     } 
    } 

    if !alreadyRunning { 
     let path = Bundle.main.bundlePath 
     let index = path.index(path.endIndex, offsetBy:-22) 
     var newPath = path.substring(to: index) 
     newPath += "login-item.app" 
     NSWorkspace.shared().launchApplication(newPath) 
    } 
    NSApp.terminate(nil) 
} 

如果獨立運行,發射成功啓動主應用程序。其他配置(如構建階段)均按教程建議的方式完成,其中包括this之一。我還啓用了沙箱選項,我使用我的開發標識簽署了應用程序,並從「應用程序」文件夾運行應用程序。它按預期工作,但在註銷並重新登錄時不會啓動。

回答

0

首先,建議實施啓用/禁用功能的複選框。

在macOS中,使用Cocoa Bindings非常簡單。實施此方法並將其綁定到複選框的value

let helperBundleIdentifier = "abc.loginItem-launcher" 

@available(OSX, deprecated: 10.10) // necessary to suppress the deprecated warning. 
dynamic var startAtLogin : Bool { 
    get { 
    guard let jobDicts = SMCopyAllJobDictionaries(kSMDomainUserLaunchd).takeRetainedValue() as NSArray as? [[String:Any]] else { return false } 
    return jobDicts.filter { $0["Label"] as! String == helperBundleIdentifier }.isEmpty == false 
    } set { 
    if !SMLoginItemSetEnabled(helperBundleIdentifier as CFString, newValue) { 
     print("SMLoginItemSetEnabled failed.") 
    } 
    } 
} 

要解決您的問題,請啓動Console.app並查看system.log。如果存在多個條目無法解析服務指定的CFBundleIdentifier ...有關應用程序的包標識符,請確保/ Applications中的應用程序是唯一的副本。刪除所有其他人的檔案等


在助手應用程序這一塊的代碼

var alreadyRunning:Bool = false 
for app in NSWorkspace.shared().runningApplications{ 
    if app.bundleIdentifier == "abc.login-item"{ 
     alreadyRunning = true 
     break 
    } 
} 

if !alreadyRunning { 

可以減少 - 由於斯威夫特 - 以

if NSRunningApplication.runningApplications(withBundleIdentifier: "abc.login-item").isEmpty { ... 
+0

我的應用程序_must_在登錄時運行,用戶不能關閉它,所以我不會實現一個複選框。我不確定是否將此標記爲正確,我的代碼現在可以正常工作(不會更改我發佈的內容),但確實在刪除所有其他存檔時使用了您的建議。之後重新啓動,併成功。謝謝。 – theQuestions

+0

這裏是macOS開發的新手。我花了大量的時間發現「Build」字段的「0.1.1」導致_「Could not resolve ...」_問題。希望我會知道預計會有一個數字值! – Nate