swift SecItemCopyMatching 的 2.0 钥匙串类型错误

swift 2.0 keychain type errors for SecItemCopyMatching

我们在 Swift

的先前版本中使用了这段代码
    var retrievedData: NSData?
    var extractedData: Unmanaged<AnyObject>? = nil
    let status = SecItemCopyMatching(keyChainQuery, &extractedData)

    if (status == errSecSuccess) {
        if let validExtractedData = extractedData {
            let opaque = validExtractedData.toOpaque()
            retrievedData = Unmanaged<NSData>.fromOpaque(opaque).takeUnretainedValue()
        }
    }

然而,这给了我们以下错误:

Cannot convert value of type 'inout Unmanaged?' (aka 'inout Optional>') to expected argument type 'UnsafeMutablePointer' (aka 'UnsafeMutablePointer>')

我有点不知道如何修复它。 我想我必须分配一些内存,为它创建一个 UnsafeMutablePointer,然后将其提供给 SecItemCopyMatching?

我试过这个:

    let sizeOfKey = 32
    var store = NSMutableData(capacity: sizeOfKey)!
    let status = SecItemCopyMatching(keyChainQuery, store.bytes)

但这给了我一个:

Cannot convert value of type 'UnsafePointer' (aka 'UnsafePointer<()>') to expected argument type 'UnsafeMutablePointer' (aka 'UnsafeMutablePointer>') error

有人有想法吗?

经过更多的思考,我想出了这个解决方案:

    var retrievedData: NSData?
    let sizeOfKey = 32
    let store = UnsafeMutablePointer<AnyObject?>.alloc(sizeof(AnyObject?) * sizeOfKey)
    let status = SecItemCopyMatching(keyChainQuery, store)

    if (status == errSecSuccess) {
        retrievedData = NSData(bytesNoCopy: store, length: sizeOfKey, freeWhenDone: true)
    }

编译。我不确定它是否真的有效。如果是这样,我会更新这个 post。同时,如果知情人士可以对此发表评论,那就太好了!

看来,我们不需要Unmanaged<>工作了。

尝试:

var retrievedData: NSData?
var extractedData: AnyObject?
let status = SecItemCopyMatching(keyChainQuery, &extractedData)

if (status == errSecSuccess) {
    retrievedData = extractedData as? NSData
}