cannot invoke initializer for Unmanaged<AnyObject>? with no arguments in swift

你。 提交于 2020-05-18 20:16:30

问题


what I want is to convert RSA Sec key into base64 encoded string with swift. so I initialized a variable like below,

var publicKeyBits = Unmanaged<AnyObject>?()

then it gives

cannot invoke initializer for Unmanaged? with no arguments in swift

I want to covert my publickey like below

var publicKeyBits = Unmanaged<AnyObject>?()
SecItemCopyMatching(queryAttrs, &publicKeyBits)

let opaqueBits = publicKeyBits?.toOpaque() 
let publicKeyData = Unmanaged<NSData>.fromOpaque(opaqueBits).takeUnretainedValue()

let publicKeyBase64 = publicKeyData.base64EncodedData(NSDataBase64EncodingOptions.Encoding64CharacterLineLength)

error. any idea of this.


回答1:


SecItemCopyMatching is declared as

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

so you have to pass the address of a CFTypeRef? as inout argument. (In early Swift versions this function returned an unmanaged object, that is no longer the case.)

You retrieve the item as a CFTypeRef (a typealias for AnyObject) and then cast it to the actual type. Example:

var result: CFTypeRef?
let status = SecItemCopyMatching(queryAttrs, &result)
if status == errSecSuccess {
    if let publicKeyData = result as? Data {
        let base64 = publicKeyData.base64EncodedString()
    }
}



回答2:


You need to check the initialization of Unmanaged class, there might be some initialization parameters.

var publicKeyBits = Unmanaged<AnyObject>("mykey")


来源:https://stackoverflow.com/questions/45813984/cannot-invoke-initializer-for-unmanagedanyobject-with-no-arguments-in-swift

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!