SecItemCopyMatching的swift 2.0 keychain类型错误

时间:2015-09-03 14:10:30

标签: swift keychain swift2

我们在以前的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()
        }
    }

但是现在这给我们带来了以下错误:

  

无法转换类型&#39; inout Unmanaged?&#39; (又名   &#39; inout可选&gt;&#39;)到预期的参数类型   &#39; UnsafeMutablePointer&#39; (又名   &#39;&UnsafeMutablePointer GT;&#39)

我对如何修复它感到有点迷茫。 我假设我必须分配一些内存,为它创建一个UnsafeMutablePointer,然后将它提供给SecItemCopyMatching?

我试过了:

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

但这给了我一个:

  

无法转换类型&#39; UnsafePointer&#39;的值(又名   &#39; UnsafePointer&lt;()&gt;&#39;)到期望的参数类型   &#39; UnsafeMutablePointer&#39; (又名   &#39; UnsafeMutablePointer&gt;&#39;)错误

有人有想法吗?

2 个答案:

答案 0 :(得分:26)

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

尝试:

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

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

答案 1 :(得分:0)

在经历了一些困惑之后,我提出了这个解决方案:

    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)
    }

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