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

4 comments:

  1. can you first highlight the parts to be replaced with the application whose dock we're hiding, and then for newbies to cocoa like me, explain in simple terms how to implement this.

    seems to me that if this method works, someone should write a simple mavericks cocoa app to replace utilities like dockutil. i'd pay for it. hell i'll pay one of you code geniuses to make it! what's the hold-up?!

    ReplyDelete
    Replies
    1. I wrote this when dockutil was failing sometime back. However, the bug in dockutil is now fixed and they have released the new version with 10.9 support.
      https://github.com/kcrawford/dockutil

      Delete
  2. How could I achieve same in the higher os versions.
    I want to do the same on the 10.11, 10.12, 10.13

    thnks
    vikram sinha

    ReplyDelete
  3. How could I achieve this in higher os versions.
    Like 10.11, 10.12, 10.13

    Thanks
    Vikram Sinha

    ReplyDelete