Skip to content

Instantly share code, notes, and snippets.

@erica
Last active August 29, 2015 14:18
Show Gist options
  • Save erica/7c298164409795bbf92f to your computer and use it in GitHub Desktop.
Save erica/7c298164409795bbf92f to your computer and use it in GitHub Desktop.
Launch at Login Helper
//
// LaunchAtLoginHelper.swift
//
// Created by Erica Sadun on 4/1/15.
// Copyright (c) 2015 Erica Sadun. All rights reserved.
//
import Foundation
public func getLoginItems() -> LSSharedFileList? {
let allocator : CFAllocator! = CFAllocatorGetDefault().takeUnretainedValue()
let kLoginItems : CFString! = kLSSharedFileListSessionLoginItems.takeUnretainedValue()
var loginItems_ = LSSharedFileListCreate(allocator, kLoginItems, nil)
if loginItems_ == nil {return nil}
let loginItems : LSSharedFileList! = loginItems_.takeRetainedValue()
return loginItems
}
public func existingItem(itemURL : NSURL) -> LSSharedFileListItem? {
let loginItems_ = getLoginItems()
if loginItems_ == nil {return nil}
let loginItems = loginItems_!
var seed : UInt32 = 0
let currentItems = LSSharedFileListCopySnapshot(loginItems, &seed).takeRetainedValue() as NSArray
for item in currentItems {
let resolutionFlags : UInt32 = UInt32(kLSSharedFileListNoUserInteraction | kLSSharedFileListDoNotMountVolumes)
var url = LSSharedFileListItemCopyResolvedURL(item as! LSSharedFileListItem, resolutionFlags, nil).takeRetainedValue() as NSURL
if url.isEqual(itemURL) {
let result = item as! LSSharedFileListItem
return result
}
}
return nil
}
public func willLaunchAtLogin(itemURL : NSURL) -> Bool {
return existingItem(itemURL) != nil
}
public func setLaunchAtLogin(itemURL: NSURL, enabled: Bool) -> Bool {
let loginItems_ = getLoginItems()
if loginItems_ == nil {return false}
let loginItems = loginItems_!
var item = existingItem(itemURL)
if item != nil && enabled {return true}
if item != nil && !enabled {
LSSharedFileListItemRemove(loginItems, item)
return true
}
LSSharedFileListInsertItemURL(loginItems, kLSSharedFileListItemBeforeFirst.takeUnretainedValue(), nil, nil, itemURL as CFURL, nil, nil)
return true
}
@avinassh
Copy link

avinassh commented Apr 2, 2015

Hi, this is av_ from IRC. I tried above code and it works with my app, thank you very much!

can I use this code in my app? Also, I had one more question, login items can be handled using ServiceManagement also, but does that require code to be signed using Mac Dev program?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment