2016-07-26 59 views
1

我一直在一個問題上掙扎了一段時間。我不知道爲什麼這樣的代碼:withUnsafeMutablePointer does not compile

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告訴我說:

無法將類型的「價值INOUT CFArray? 「 (又名「INOUT可選」)預期的參數類型「INOUT _」

我真的不看2碼怎麼是可變的citems不同,因爲我基本上只是做是使用一個NSData的說法該函數,從而繞過base64字符串轉換爲NSData。

回答

1

錯誤消息是超級混亂,但錯誤的原因所在位置:

SecPKCS12Import(p12KeyFileContent!, options, citemsPtr) 

在你的第二個例子,與聲明let p12KeyFileContent = NSData(data: base64p12)p12KeyFileContent類型是NSData,不NSData?。所以,你不能使用!作爲p12KeyFileContent

嘗試改變路線爲:

SecPKCS12Import(p12KeyFileContent, options, citemsPtr) 

!除去。)


一個。

您通常不需要使用withUnsafeMutablePointer致電SecPKCS12Import

嘗試更換(在第二實例)這3行:

let resultPKCS12Import = withUnsafeMutablePointer(&citems) { citemsPtr in // line with the error 
    SecPKCS12Import(p12KeyFileContent!, options, citemsPtr) 
} 

與此:

let resultPKCS12Import = SecPKCS12Import(p12KeyFileContent, options, &citems) 

第一個例子的代碼也可被重寫。