How to return a dictionary through a `UnsafeMutablePointer<cftyperef?>?` parameter?

时间:2018-09-18 19:41:24

标签: ios swift xcode foundation

For tests I created a mock class which wraps the Security framework functions. Everything works fine except for my attempted fake of SecItemCopyMatching(_:_:). The full signature is:

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

I do not want to use SecItemCopyMatching(_:_:) of the Security framework but implement a dummy with the same signature for testing by myself.

The following snippet is from the official documentation on how to process the functions result. I do not know how to render a dummy Dictionary through the UnsafeMutablePointer to be used the same way. I cannot assign anything to the pointer and am confused by the UnsafeMutablePointer<CFTypeRef?>? - is that a pointer to a pointer?

guard let existingItem = item as? [String : Any],
    let passwordData = existingItem[kSecValueData as String] as? Data,
    let password = String(data: passwordData, encoding: String.Encoding.utf8),
    let username = existingItem[kSecAttrAccount as String] as? String
    else {
        throw KeychainError.unexpectedPasswordData
}

2 个答案:

答案 0 :(得分:0)

I think You will get your answer at below stack over flow post

UnsafeMutablePointer<CFTypeRef> in Swift 3

and its a pointer to a variable.

答案 1 :(得分:0)

我找到的有效解决方案:

func SecItemCopyMatching(_ query: CFDictionary, _ result: UnsafeMutablePointer<CFTypeRef?>?) -> OSStatus {
    let item: [String: Any] = [
        kSecAttrAccount as String: "username",
        kSecValueData as String: "password".data(using: String.Encoding.utf8)!
    ]

    result?.pointee = item as AnyObject
    return copyMatchingStatus
}

他们了解的关键信息:CFTypeRef直接映射到AnyObject(请参阅Working with Core Foundation Types)。将字典强制转换为AnyObject即可将其指定为pointee。