7

在带有 Swift 的 Xcode 6 和 7 的早期版本中,这种语法可以工作:

    var secureItemValue: Unmanaged<AnyObject>?

    let statusCode: OSStatus = SecItemCopyMatching(keychainItemQuery, &secureItemValue)
    if statusCode == errSecSuccess
    {
        let opaquePointer = secureItemValue?.toOpaque()

        let secureItemValueData = Unmanaged<NSData>.fromOpaque(opaquePointer!).takeUnretainedValue()

        // Use secureItemValueData...
    }

但是,SecItemCopyMatching 声明在 Xcode 7 beta 4 中发生了变化:

老的: func SecItemCopyMatching(_ query: CFDictionary, _ result: UnsafeMutablePointer<AnyObject?>) -> OSStatus

新的: func SecItemCopyMatching(_ query: CFDictionary!, _ result: UnsafeMutablePointer<Unmanaged<AnyObject>?>) -> OSStatus

...现在 secureItemValue 类型不匹配。

该机制在提取结果之前令人困惑,我希望新声明更容易,但我不知道如何为secureItemValue变量声明正确的类型并提取结果。

4

2 回答 2

18

这适用于 Xcode 7 beta 4

var dataTypeRef: AnyObject?

    let status: OSStatus = withUnsafeMutablePointer(&dataTypeRef) { SecItemCopyMatching(keychainQuery as CFDictionaryRef, UnsafeMutablePointer($0)) }

    if status == noErr {
        return dataTypeRef as? NSData
    }
    else {
        return nil
    }
于 2015-07-21T21:49:48.637 回答
4

根据这个答案,您可以Unmanaged<>在 AnyObject 周围删除:

var secureItemValue: AnyObject?

let statusCode: OSStatus = SecItemCopyMatching(keychainItemQuery, &secureItemValue)
于 2015-11-23T14:49:10.737 回答