0

我正在尝试为 Swift iOS 应用程序生成和获取密钥对信息,并且在设置时遇到UnsafeMutablePointer以下错误:

无法将“UnsafeMutablePointer<_>”类型的值转换为预期的参数类型“UnsafeMutablePointer<CFTypeRef?>?” (又名'可选<UnsafeMutablePointer<可选<AnyObject>>>')

我正在尝试利用以下 StackOverflow 讨论来使其正常工作: Generate a CSR in iOS Library?

我的问题是如何明确设置值来纠正这个错误?

以下是我尝试使用的以下代码:

//Locates the SecKeyRef to the key passed in and returns secKeyRef

func readSecKeyRefFromKeychain(searchKey: String) -> SecKey
{
    let keyQuery: Dictionary<String, AnyObject> = [
        String(kSecAttrKeyType):kSecAttrKeyTypeRSA,
        String(kSecAttrKeySizeInBits):KEY_SIZE as AnyObject,
        String(kSecClass):kSecClassKey,
        String(kSecAttrApplicationTag):searchKey as AnyObject,
        kSecReturnRef as String : kCFBooleanTrue
    ]

    var dataTypeReference: Unmanaged<AnyObject>? = nil
    var dataResult: SecKey? = nil

    let status: OSStatus = withUnsafeMutablePointer(to:&dataTypeReference)
    {
        SecItemCopyMatching(keyQuery as NSDictionary, UnsafeMutablePointer($0))
    }
    NSLog("readSecKeyRefFromKeychain: SecItemCopyMatching: " + status.description)

    if status == errSecSuccess{
        NSLog("key debug description is: " + dataTypeReference.debugDescription)
        dataResult = (dataTypeReference!.takeRetainedValue() as! SecKey)
        NSLog("public or private secKeyRef is: " + dataResult.debugDescription)
        return dataResult!
    }else{
        return dataResult!
    }
}
4

1 回答 1

0

这个?

//Locates the SecKeyRef to the key passed in and returns secKeyRef

func readSecKeyRefFromKeychain(searchKey: String) -> SecKey {
    let keyQuery: Dictionary<String, AnyObject> = [
        String(kSecAttrKeyType):kSecAttrKeyTypeRSA,
        String(kSecAttrKeySizeInBits):KEY_SIZE as AnyObject,
        String(kSecClass):kSecClassKey,
        String(kSecAttrApplicationTag):searchKey as AnyObject,
        kSecReturnRef as String : kCFBooleanTrue
    ]

    var dataTypeReference: Unmanaged<AnyObject>? = nil
    var dataResult: SecKey? = nil

    let status: OSStatus = withUnsafeMutablePointer(to:&dataTypeReference) {
        SecItemCopyMatching(query as NSDictionary, ($0 as CFTypeRef) as? UnsafeMutablePointer<CFTypeRef?>)
    }

    NSLog("readSecKeyRefFromKeychain: SecItemCopyMatching: " + status.description)

    if status == errSecSuccess {
        NSLog("key debug description is: " + dataTypeReference.debugDescription)
        dataResult = (dataTypeReference!.takeRetainedValue() as! SecKey)
        NSLog("public or private secKeyRef is: " + dataResult.debugDescription)
        return dataResult!
    } else {
        return dataResult!
    }
}
于 2020-04-21T18:54:55.550 回答