Looping through a CFArray of CFURL

1.3k Views Asked by At

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?

2

There are 2 best solutions below

1
vadian On BEST ANSWER

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)
}
0
Andrew_STOP_RU_WAR_IN_UA On

all you need is to do:

let urls = cfArr as? Array<URL>

sample:

if let retainedArr = LSCopyApplicationURLsForURL(URL(fileURLWithPath: "/Users/uks/Desktop/taopixie4.png") as CFURL, .all)?.takeRetainedValue(),

let listOfRelatedApps = retainedArr as? Array<URL>