1

我在访问 CFDictionary 中的特定(或任何)键时遇到问题。老实说,我真的不明白你需要在 Swift 中执行此操作的方式,而且我认为它过于复杂......

我的代码:

if let session = DASessionCreate(kCFAllocatorDefault) {
let mountedVolumes = FileManager.default.mountedVolumeURLs(includingResourceValuesForKeys: [], options: [])!
for volume in mountedVolumes {
    if let disk = DADiskCreateFromVolumePath(kCFAllocatorDefault, session, volume as CFURL) {
        let diskinfo = DADiskCopyDescription(disk);   

        var volumeValue = CFDictionaryGetValue(diskinfo, <#T##key: UnsafeRawPointer!##UnsafeRawPointer!#>)


    }
}

我想要实现的目标:将键或字段DAVolumeNetwork的值获取到变量volumeValue中。我想我需要将kDADiskDescriptionVolumeNetworkKey传递给CFDictionaryGetValue方法?我如何实现这一目标?

4

2 回答 2

3

不要CFDictionary在 Swift 中使用。(这是可能的,但不值得努力,见下文。)

  • CFDictionary与免费桥接NSDictionary,而后者又可以转换为 Swift Dictionary
  • 键的值kDADiskDescriptionVolumeNetworkKey是 a CFBoolean可以转换为 Swift Bool

例子:

if let session = DASessionCreate(kCFAllocatorDefault),
    let mountedVolumes = FileManager.default.mountedVolumeURLs(includingResourceValuesForKeys: []) {
    for volume in mountedVolumes {
        if let disk = DADiskCreateFromVolumePath(kCFAllocatorDefault, session, volume as CFURL),
            let diskinfo = DADiskCopyDescription(disk) as? [NSString: Any] {

            if let networkValue = diskinfo[kDADiskDescriptionVolumeNetworkKey] as? Bool {
                print(networkValue)
            }
        }
    }
}

只是为了完整起见:这是CFDictionaryGetValue在 Swift 3 中调用的必要指针杂耍:

if let session = DASessionCreate(kCFAllocatorDefault),
    let mountedVolumes = FileManager.default.mountedVolumeURLs(includingResourceValuesForKeys: []) {
    for volume in mountedVolumes {
        if let disk = DADiskCreateFromVolumePath(kCFAllocatorDefault, session, volume as CFURL),
            let diskinfo = DADiskCopyDescription(disk) {

            if let ptr = CFDictionaryGetValue(diskinfo, Unmanaged.passUnretained(kDADiskDescriptionVolumeNetworkKey).toOpaque()) {
                let networkValue = Unmanaged<NSNumber>.fromOpaque(ptr).takeUnretainedValue()
                print(networkValue.boolValue)
            }
        }
    }
}
于 2017-03-14T13:08:08.037 回答
0

您可以CFDictionaryRef转换为 Swift 字典:

if let disk = DADiskCreateFromVolumePath(kCFAllocatorDefault, session, volume as CFURL), let diskinfo = DADiskCopyDescription(disk) as? [String: AnyObject] {
}

然后kDADiskDescriptionVolumeNetworkKey转换为 Swift 字符串:

var volumeValue = diskinfo[kDADiskDescriptionVolumeNetworkKey as String]
于 2017-03-14T13:08:31.750 回答