swiftxcodecore-services

Error while obtaining URL/path of app using LSCopyApplicationURLsForBundleIdentifier and CFArrayGetValueAtIndex


I am using LSCopyApplicationURLsForBundleIdentifier to get the URL(s) of an installed third-party app on the target system based on its bundle identifier. However, when trying to retrieve the first URL from the returned CFArray, I keep getting the following error in the debugger at CFArrayGetValueAtIndex:

Thread 1: EXC_BAD_INSTRUCTION (code=EXC_I386_INVOP, subcode=0x0)

Here is the section of my Swift code:

let urls = LSCopyApplicationURLsForBundleIdentifier("com.aa.bb" as CFString, nil)
if (urls != nil) {
     let url = unsafeBitCast(CFArrayGetValueAtIndex(urls as! CFArray, 0), to: CFString.self)
}
urls?.release()
url?.release()

How can I extract the URL correctly, preferably as String?


Solution

  • Too complicated, get the pointee with takeRetainedValue() – which handles the memory management properly – and cast it to [URL]

    if let urls = LSCopyApplicationURLsForBundleIdentifier("com.aa.bb" as CFString, nil)?.takeRetainedValue() as? [URL],
       let url = urls.first {
         print(url)
    }
    

    An unsafeBitCast from (CF)URL to (CF)String is impossible anyway, to get a string path write

    print(url.path)