5

我正在尝试调用SecItemCopyMatching我的钥匙串实用程序类以从钥匙串中获取数据,但我在获取result参数时遇到了问题,UnsafeMutablePointer<CFTypeRef?>.

最初的声明(在 Swift 2 中,在迁移到 Swift 3 之前)是

// query is a dictionary of [String : AnyObject]

var result: Data?
let status = withUnsafeMutablePointer(to: &result) {
    SecItemCopyMatching(query as CFDictionary, UnsafeMutablePointer($0))
}

但在 Swift 3 中,您现在需要调用.withMemoryRebound才能查看内存。根据 Xcode 告诉您的操作,我尝试了这个

var result: Data?
let status = withUnsafeMutablePointer(to: &result){
    $0.withMemoryRebound(to: Data.self, capacity: 1){
        SecItemCopyMatching(query as CFDictionary, UnsafePointer($0))
    }
}

然而这样做,我得到一个错误

无法将类型“ UnsafePointer<_>”的值转换为预期的参数类型“ UnsafeMutablePointer<CFTypeRef?>?

所以,我尝试使用CFTypeRef而不是Data

var result: CFTypeRef?
let status = withUnsafeMutablePointer(to: &result){
    $0.withMemoryRebound(to: CFTypeRef.self, capacity: 1){
        SecItemCopyMatching(query as CFDictionary, UnsafePointer($0))
    }
}

替换UnsafePointer($0)为简单$0会导致相同的错误消息。

如何UnsafeMutablePointer<CFTypeRef?>从钥匙串中获取数据?

4

2 回答 2

12

在您的情况下,您不需要使用withMemoryReboundor withUnsafeMutablePointer(to:)

相反,您可以使用

var result: AnyObject?
let status = SecItemCopyMatching(query as CFDictionary, &result)

if status == noErr, let data = result as? Data {
    //use data...
}

通常,当您需要将 an 传递UnsafeMutablePointer<T>给函数时,声明一个类型的变量T并将其作为 inout 参数传递&variable。在您的情况下,Tis CFTypeRef?,在 Swift 3 中,CFTypeRef只是AnyObject.


即使在 Swift 2.2 中,您也不需要使用withUnsafeMutablePointer

var result: AnyObject?  
let status = SecItemCopyMatching(query, &result)  
于 2016-09-12T10:43:42.427 回答
1

该错误消息有些误导 - 实际问题是result必须是AnyObject?-withMemoryRebound不需要使用。

var result: AnyObject?
let status = withUnsafeMutablePointer(to: &result){
    SecItemCopyMatching(query as CFDictionary, UnsafeMutablePointer($0))
}

按预期工作并从钥匙串中获得正确的结果-只需将其转换为Data. 事实上,withUnsafeMutablePointer甚至不必使用.

所以,我的新代码是

var query: [String : AnyObject] = [:]
//set up the query

var result: AnyObject?
let status = SecItemCopyMatching(query as CFDictionary, &result)

var data: Data?
if status == noErr{
    data = result as? Data
}
于 2016-09-12T00:48:00.653 回答