0

I am getting a headache due to UnsafePointer in Swift.

This is the method I want to call:

func CFDictionaryGetValue(theDict: CFDictionary!, _ key: UnsafePointer<Void>) -> UnsafePointer<Void>

And this is how I do it.

 let ds: SCDynamicStoreRef = SCDynamicStoreCreate(nil, "setNet" as CFString, nil, nil)!


let list = SCDynamicStoreCopyProxies(ds)

print(list!)
print(CFDictionaryGetValue(list, UnsafePointer("HTTPPort")))

This however returns an error. I have no idea how to pass dictionary key to this method. If I remove the UnsafePointer("HTTPPort") and use "HTTPPort" instead I get a runtime error."

How can you access the dictionary values?

potato
  • 4,479
  • 7
  • 42
  • 99

1 Answers1

1

The easiest solution is to take advantage of the toll-free bridging between CFDictionary and NSDictionary, and use the NSDictionary accessor methods:

let ds = SCDynamicStoreCreate(nil, "setNet", nil, nil)!

if let list = SCDynamicStoreCopyProxies(ds) as NSDictionary? {
    if let port = list[kSCPropNetProxiesHTTPPort as NSString] as? Int {
        print("HTTPPort:", port)
    }
}

But just for the sake of completeness: It can be done with CFDictionaryGetValue:

if let list = SCDynamicStoreCopyProxies(ds)  {
    let key = kSCPropNetProxiesHTTPPort
    let port = unsafeBitCast(CFDictionaryGetValue(list, unsafeAddressOf(key)), NSObject!.self)
    if port != nil {
        print("HTTPPort:", port)
    }
}
Martin R
  • 529,903
  • 94
  • 1,240
  • 1,382
  • It turned out that the dictionary returned is read only. If you have time and are know about system configuration framework feel free to look at http://stackoverflow.com/questions/36175502/set-current-proxy-settings – potato Mar 23 '16 at 10:28