Restart your Cocoa application using Sparkle

June 03, 2010

It’s not uncommon for an OS X application to need to restart itself in certain unavoidable situations, such as hiding the dock icon. Most of the solutions you’ll find on the Internet rely on a command line helper app that waits for the parent application to finish exiting before launching it again. Although this isn’t hard to implement yourself, chances are you already have everything you need, buried inside the Sparkle framework.

Based on the Sparkle source code, here’s a quick way to restart any application that includes the Sparkle framework.

NSString *launcherSource = [[NSBundle bundleForClass:[SUUpdater class]]  pathForResource:@"relaunch" ofType:@""];
NSString *launcherTarget = [NSTemporaryDirectory() stringByAppendingPathComponent:[launcherSource lastPathComponent]];
NSString *appPath = [[NSBundle mainBundle] bundlePath];
NSString *processID = [NSString stringWithFormat:@"%d", [[NSProcessInfo processInfo] processIdentifier]];

[[NSFileManager defaultManager] removeItemAtPath:launcherTarget error:NULL];
[[NSFileManager defaultManager] copyItemAtPath:launcherSource toPath:launcherTarget error:NULL];

[NSTask launchedTaskWithLaunchPath:launcherTarget arguments:[NSArray arrayWithObjects:appPath, processID, nil]];
[NSApp terminate:sender];

If you’re not using Sparkle, here’s a complete implementation of this idea you may find helpful.

Marc Charbonneau is a mobile software engineer in Portland, OR. Want to reply to this article? Get in touch on Twitter @mbcharbonneau.