Wednesday, December 23, 2015


I came across another introductory article about how to import CommonCrypto from Swift.

Recall what we did before following this post:

Method 1:

- obtain a bridging header by adding a dummy Objective-C file in Xcode
- in the header, do #import <CommonCrypto/CommonCrypto.h>

The library functions will be available from an Xcode Swift Cocoa app project.

Method 2:

Make CommonCrypto quack like a Framework by putting a file with appropriate code, inside the directory that holds OS X SDK frameworks:


With that single change:

- we no longer need the bridging header from an Xcode project
- we can use CommonCrypto in a framework
- we can use it in an Xcode Playground

- we can also do this:

import CommonCrypto

> swift test.swift

The referenced article shows a different way to use CommonCrypto inside a framework (where the bridging header trick won't work).

Put the
module CommonCrypto [system] {
header "/usr/include/CommonCrypto/CommonCrypto.h"
export *

inside your project directory (not necessary to use Xcode). Following the instructions:

Now add the new module to Import Paths under Swift Compiler – Search Paths in your project settings. Use ${SRCROOT} in the module path (e.g. ${SRCROOT}/CommonCrypto) to insure that the project works no matter where it’s checked out.

Then you can just use import CommonCrypto.

Other notable items:

- use of NSData and NSMutableData types for the buffers
- size_t(key.length) and size_t(data.length), in calling the functions

No comments: