Over the last few weeks I've been writing a mac application in swift, both to get into mac programming and to practice swift for when we migrate over to it at my workplace. I'm currently trying to get some code working to add my application as a "Launch on Startup" application by tailoring code kindly provided over on BDungan's blog
So far after messing about for many hours I have come up with the following:
func itemRefInLoginItems () -> LSSharedFileListItemRef?
{
var itemRef: LSSharedFileListItemRef? = nil
var itemURL: Unmanaged<CFURLRef>?
let appURL = NSURL.fileURLWithPath(NSBundle.mainBundle().bundlePath)
if let loginItemsRef = LSSharedFileListCreate(kCFAllocatorDefault,kLSSharedFileListSessionLoginItems.takeRetainedValue(),NSMutableDictionary()) {
var unretainedLoginItemsRef = loginItemsRef.takeUnretainedValue()
if var loginItems = LSSharedFileListCopySnapshot(unretainedLoginItemsRef, nil) {
for item in (loginItems.takeRetainedValue() as NSArray) {
let currentItemRef = item as LSSharedFileListItemRef
var outRef: FSRef
if (LSSharedFileListItemResolve(currentItemRef, 0, &itemURL, nil) == noErr) {
if (appURL?.isEqual(itemURL?.takeRetainedValue()) != nil) { //PROBLEM 1
itemRef = currentItemRef
}
}
}
}
}
return itemRef
}
func isLaunchAtStartup () -> Bool {
let itemRef = self.itemRefInLoginItems()
return itemRef != nil
}
func makeLaunchAtStartup () { // Compile seems to fall down on this line...
if !self.isLaunchAtStartup() {
let loginItemsRef = LSSharedFileListCreate(kCFAllocatorDefault, kLSSharedFileListSessionLoginItems.takeRetainedValue(), NSMutableDictionary())
let appURL = NSURL(fileURLWithPath: NSBundle.mainBundle().bundlePath) as CFURLRef
let itemRef = LSSharedFileListInsertItemURL(loginItemsRef.takeRetainedValue(), kLSSharedFileListItemLast.takeRetainedValue(), nil, nil, appURL, nil, nil)
}
}
I am running into two problems however.
Problem 1
Swift does not want me to compare an NSURL to a CFURLRef... for now I went with an Xcode suggestion just to get the app running, but I'm 100% sure it isn't doing what I think it is. (see //PROBLEM 1).
In objective-c it seems toll free bridging was allowed between NSURL and CFURLRef (or CFURL), however on attempt to cast, conditional cast or any variety of swift as(Insert correct character here) approaches my code inevitably wouldn't build. I get errors such as:
Unmanaged is not a subtype of NSURL:
if appURL as Unmanaged<CFURLRef> == itemURL
e.t.c.
Problem 2
Although this code currently gives no warnings or errors... when trying to compile I get a Command failed due to signal: Segmentation fault: 11
, which to be frank... is beyond me.