Search code examples
cocoaurlfoundationbundle-identifierapp-bundle

How do I use Cocoa to get a URL of a bundle with a given ID, or vice versa?


If I have a bundle identifier as a String, how do I find out the URL of the bundle that it identifies? Conversely, if I have the URL of a bundle, how do I find out that bundle's identifier as a String?

I would like to only use Foundation/Cocoa APIs to do this.


Solution

  • You can use Bundle's init(identifier:) followed by bundleURL to get a URL from a bundle identifier, and Bundle's init(url:) followed by bundleIdentifier to get a bundle's URL.

    Example:

    let myBundleUrl = Bundle(identifier: "com.me.app")?.bundleURL
    
    let theirBundleId = Bundle(url: URL(fileURLWithPath: "/Applications/Mail.app"))?.bundleIdentifier
    

    Just as a note, NSWorkspace also has an API for getting a URL from a given bundle ID: urlForApplication(withBundleIdentifier:). I didn't recommend this one here because NSWorkspace doesn't have an API for getting an identifier from a URL.