Sunday 9 March 2014

Removing dock icon using Cocoa

Sometimes there is a need of removing a dock icon programmatically. In such cases, there are third party utilities like dockutil, available to do the task. However, there was a problem in OSX Mavericks (Mac 10.9) where dockutil failed to remove the icon from the dock. [Update: The issue in dockutil is fixed in their latest version]
If any of you faced a similar issue, you can use the Cocoa APIs to remove the dock icon right from your code. See the sample code below-




-(void) removeDockIcon: (NSString*) dockIconName
{ 
 NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];

 NSDictionary* dockDict = [userDefaults persistentDomainForName:@"com.apple.dock"];

 NSMutableArray* apps = [dockDict valueForKey:@"persistent-apps"];
 if (apps != nil)
 { 
  NSArray* appsCopy = [apps copy];
  bool modified = NO;
  for(NSDictionary *anApp in appsCopy)
  {
   NSDictionary* fileDict = [anApp valueForKey:@"tile-data"];
   if(fileDict != nil)
   {
    NSString *appName = [fileDict valueForKey:@"file-label"];

    if([dockIconLabel isEqualToString:appName])
    {
     [apps removeObject:anApp];
     modified = YES;
     break;
    }
   }
  }
  if(modified)
  {
   //If the dictionary was modified, save the new settings.
   [userDefaults setPersistentDomain:dockDict forName:@"com.apple.dock"];
   //Reset the standardUserDefaults so that the modified data gets synchronized
   //and next time when this function is invoked, we get the up-to-date dock icon details.
   [NSUserDefaults resetStandardUserDefaults];
  }
 }
}


NOTE: It is a sample code written when I didn't have access to my Mac. Please do the necessary cleanup and fix syntax errors if any.
UPDATE: dockutil now has the fix for this issue. https://github.com/kcrawford/dockutil