nsij22
nsij22

Reputation: 879

How do you import a DER certificate in swift?

So it seems as though a bunch of methods have changed which have broken things in my current codebase. I'm currently getting the following error:

Cannot convert the expression's type '(CFAllocator!, data: @lvalue NSData)' to type 'CFData!'

Here's the relevant code:

let mainbun = NSBundle.pathForResource("mainkey", ofType: "der", inDirectory: "/myapppath")
var key: NSData = NSData(base64EncodedString: mainbun!, options: nil)!
var turntocert: SecCertificateRef = SecCertificateCreateWithData(kCFAllocatorDefault, data: key)

I have it working with a bridging header but i would still like to just be able to create the certificate reference directly in swift.


UPDATE: this works

var bundle: NSBundle = NSBundle.mainBundle()
var mainbun = bundle.pathForResource("keyfile", ofType: "der")
var key: NSData = NSData(contentsOfFile: mainbun!)!
var turntocert: SecCertificateRef =
SecCertificateCreateWithData(kCFAllocatorDefault, key).takeRetainedValue()

Upvotes: 5

Views: 5294

Answers (1)

bbarnhart
bbarnhart

Reputation: 6710

In Swift, SecCertificateCreateWithData returns an Unmanaged type. You need to get the value of the unmanaged reference with takeRetainedValue().

let mainbun = NSBundle.pathForResource("mainkey", ofType: "der", inDirectory: "/myapppath")
var key: NSData = NSData(base64EncodedString: mainbun!, options: nil)!
var turntocert: SecCertificateRef = 
    SecCertificateCreateWithData(kCFAllocatorDefault, key).takeRetainedValue()

The core problem you have is converting CFData to NSData. See this question

Upvotes: 5

Related Questions