swiftcore-services

Looping through a CFArray of CFURL


Using Swift, I'm trying to loop through a CFArray of CFURLs but I'm getting a EXC_BAD_INSTRUCTION error.

let apps = LSCopyApplicationURLsForURL(NSURL(string: "http://www.yahoo.com")! as CFURL, LSRolesMask.all)!

let finalArray = apps.takeRetainedValue()

let count = CFArrayGetCount(finalArray)

for ix in 0...count-1 {
    let url = CFArrayGetValueAtIndex(finalArray, ix) as! CFURL
    print(url)
}

What am I doing wrong?


Solution

  • Do you really want to stay in the abyss of CoreFoundation? 😉 Cast the array to [URL]

    if let apps = LSCopyApplicationURLsForURL(URL(string: "http://www.yahoo.com")! as CFURL, LSRolesMask.all)?.takeRetainedValue() {
        for url in apps as! [URL] {
            print(url)
        }
    }
    

    By the way the error occurs because CFArrayGetValueAtIndex returns a pointer which cannot be cast to CFURL

    You would have to write something like

    for ix in 0..<count {
        let url = unsafeBitCast(CFArrayGetValueAtIndex(finalArray, ix), to: URL.self)
        print(url)
    }