我已经有一段时间在一个问题上挣扎了。我想知道为什么这段代码:
private func generateIdentity (base64p12 : String, password : String?, url : NSURL) {
let p12KeyFileContent = NSData(base64EncodedString: base64p12, options: NSDataBase64DecodingOptions(rawValue: 0))
if (p12KeyFileContent == nil) {
NSLog("Cannot read PKCS12 data")
return
}
let options = [String(kSecImportExportPassphrase):password ?? ""]
var citems: CFArray? = nil
let resultPKCS12Import = withUnsafeMutablePointer(&citems) { citemsPtr in
SecPKCS12Import(p12KeyFileContent!, options, citemsPtr)
}
if (resultPKCS12Import != errSecSuccess) {
print(resultPKCS12Import)
return
}
let items = citems! as NSArray
let myIdentityAndTrust = items.objectAtIndex(0) as! NSDictionary
let identityKey = String(kSecImportItemIdentity)
identity = myIdentityAndTrust[identityKey] as! SecIdentityRef
hasCertificate = true
print("cert cre", identity)
}
编译,而另一个不编译:
private func generateIdentity (base64p12 : NSData, password : String?) {
let p12KeyFileContent = NSData(data: base64p12)
let options = [String(kSecImportExportPassphrase):password ?? ""]
var citems: CFArray? = nil
let resultPKCS12Import = withUnsafeMutablePointer(&citems) { citemsPtr in // line with the error
SecPKCS12Import(p12KeyFileContent!, options, citemsPtr)
}
if (resultPKCS12Import != errSecSuccess) {
print(resultPKCS12Import)
return
}
let items = citems! as NSArray
let myIdentityAndTrust = items.objectAtIndex(0) as! NSDictionary
let identityKey = String(kSecImportItemIdentity)
identity = myIdentityAndTrust[identityKey] as! SecIdentityRef
hasCertificate = true
print("cert cre", identity)
}
XCode告诉我:
无法转换类型' in CFArray的值?' (又名' inout Optional')预期参数类型' inout _'
我真的不知道citems变量的2个代码是如何不同的,因为我基本上只是为函数使用NSData参数,从而绕过base64字符串转换为NSData。
答案 0 :(得分:1)
错误消息非常混乱,但错误原因在于:
SecPKCS12Import(p12KeyFileContent!, options, citemsPtr)
在第二个示例中,声明let p12KeyFileContent = NSData(data: base64p12)
时,p12KeyFileContent
的类型为NSData
,而不是NSData?
。因此,您无法将!
用于p12KeyFileContent
。
尝试将行更改为:
SecPKCS12Import(p12KeyFileContent, options, citemsPtr)
(!
已删除。)
再一次。
您通常无需使用withUnsafeMutablePointer
来致电SecPKCS12Import
。
尝试替换这三行(在第二个例子中):
let resultPKCS12Import = withUnsafeMutablePointer(&citems) { citemsPtr in // line with the error
SecPKCS12Import(p12KeyFileContent!, options, citemsPtr)
}
用这个:
let resultPKCS12Import = SecPKCS12Import(p12KeyFileContent, options, &citems)
第一个示例代码也可以重写。