Wednesday, December 23, 2015

CommonCrypto5

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 module.map with appropriate code, inside the directory that holds OS X SDK frameworks:


/Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform\
/Developer/SDKs/MacOSX10.11.sdk/System/Library/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:


test.swift:
import CommonCrypto
print(CC_SHA1_DIGEST_LENGTH)

> swift test.swift
20
>


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

Put the module.map

module.map:
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: