2.5 KiB
2.5 KiB
Custom Context Menus (Open With) in macOS
There are several ways to register custom context menus ("Open With" options) in macOS.
Method 1: Using Launch Services
This method uses macOS's built-in Launch Services feature:
- Open System Preferences
- Go to Keyboard > Shortcuts > Services
- Create a new service in Automator
Method 2: Using an Application Bundle
To register a custom application in the "Open With" menu, you need to create a proper application bundle with an Info.plist file.
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>CFBundleDocumentTypes</key>
<array>
<dict>
<key>CFBundleTypeExtensions</key>
<array>
<string>txt</string>
<string>md</string>
</array>
<key>CFBundleTypeName</key>
<string>Text Document</string>
<key>CFBundleTypeRole</key>
<string>Editor</string>
</dict>
</array>
<key>CFBundleIdentifier</key>
<string>com.yourcompany.yourapp</string>
<key>CFBundleName</key>
<string>YourApp</string>
<key>CFBundlePackageType</key>
<string>APPL</string>
<key>CFBundleShortVersionString</key>
<string>1.0</string>
<key>CFBundleVersion</key>
<string>1</string>
</dict>
</plist>
Method 3: Using UTIs (Uniform Type Identifiers)
You can also register UTIs for your application to handle specific file types. Here's an example in Swift:
import UniformTypeIdentifiers
class DocumentHandler: NSObject, UTIDocumentProvider {
func document(withContentsOfURL url: URL,
typeUti: String) throws -> AnyObject {
// Handle the document here
return NSString()
}
}
Method 4: Using defaults Command
You can use the defaults command-line tool to associate file types with applications:
# Associate .txt files with your app
defaults write com.apple.TextEdit LSHandlers -txt
your.app.bundle.identifier
Best Practices
- Always provide clear file type associations in your
Info.plist - Use unique bundle identifiers
- Provide appropriate icons for your file types
- Implement proper error handling
- Test your implementation thoroughly
Useful Tools
- Xcode - For creating application bundles
- Automator - For creating simple services
lstypecommand - For inspecting UTIsdefaultscommand - For managing file associations