2010-10-22 390 views
5

我想使用iOS安全框架與我的服務器進行安全通信。我有一個證書文件,我可以從中獲取公鑰參考。這就是我所做的。在iPad上SecTrustCreateWithCertificates崩潰

NSString *certPath = [[NSBundle mainBundle] pathForResource:@"supportwarriors.com" ofType:@"cer"]; 
SecCertificateRef myCertificate = nil; 

NSData *certificateData = [[NSData alloc] initWithContentsOfFile:certPath]; 
myCertificate  = SecCertificateCreateWithData(kCFAllocatorDefault, (CFDataRef)certificateData); 

//got certificate ref..Now get public key secKeyRef reference from certificate.. 
SecPolicyRef myPolicy = SecPolicyCreateBasicX509(); 
SecTrustRef myTrust; 
OSStatus status  = SecTrustCreateWithCertificates(myCertificate,myPolicy,&myTrust); 

    SecTrustResultType trustResult; 
    if (status == noErr) { 
     status = SecTrustEvaluate(myTrust, &trustResult); 
    } 
publicKey  = SecTrustCopyPublicKey(myTrust); 

上面一段代碼在iPhone上完美工作,我已經測試過了。我能夠安全地與我的服務器通信。但是當我嘗試在iPad上運行我的應用程序時(以2x模式),上面的代碼崩潰了。調試後,我發現secTrustCreateWithCertificate崩潰,崩潰日誌在下面給出。我使用的證書對於iPad和iPhone都是一樣的......上面的函數返回一個證書引用並且不是零...所以這是不是崩潰的原因。我做錯了什麼。

*** -[NSCFType count]: unrecognized selector sent to instance 0x14af24 
*** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '***  -[NSCFType count]: unrecognized selector sent to instance 0x14af24' 
+0

你可以發佈證書嗎? – rook 2010-10-22 15:40:47

回答

4

SecTrustCreateWithCertificates的文檔聲稱您可以傳遞單個證書或數組。您收到的例外狀態爲-[NSCFType count]: unrecognized selector sent to instance。 iOS 3.2中發生的事情是,SecTrustCreateWithCertificates將輸入值視爲CFArray,而不先檢查是否是單數SecCertificateRef

要解決這個問題,你可以做類似下面的代碼的東西:

SecCertificateRef certs[1] = { certificate }; 
    CFArrayRef array = CFArrayCreate(NULL, (const void **) certs, 1, NULL); 
    if(SecTrustCreateWithCertificates(array, x509Policy, &trustChain) == errSecSuccess) 

只記得CFRelease(array)在適當的範圍內。