Dismiss
Announcing Stack Overflow Documentation

We started with Q&A. Technical documentation is next, and we need your help.

Whether you're a beginner or an experienced developer, you can contribute.

Sign up and start helping → Learn more about Documentation →

How do you import CommonCrypto in a Swift framework for iOS?

I understand how to use CommonCrypto in a Swift app: you add #import <CommonCrypto/CommonCrypto.h> to the bridging header.

However, Swift frameworks don't support bridging headers. The documentation says:

You can import external frameworks that have a pure Objective-C codebase, a pure Swift codebase, or a mixed-language codebase. The process for importing an external framework is the same whether the framework is written in a single language or contains files from both languages. When you import an external framework, make sure the Defines Module build setting for the framework you’re importing is set to Yes.

You can import a framework into any Swift file within a different target using the following syntax:

import FrameworkName

Unfortunately, import CommonCrypto doesn't work. Neither does adding #import <CommonCrypto/CommonCrypto.h> to the umbrella header.

share|improve this question
    
CommonCrypto is a C-based framework, not an Objective-C framework. – rmaddy Aug 11 '14 at 17:12
    
@rmaddy Objective-C is a C superset. Are you saying we can't use CommonCrypto from Swift? – hpique Aug 11 '14 at 17:25
2  
@rmaddy I just managed to get CommonCrypto working by using module maps. I will polish the solution and post it later today. – hpique Aug 11 '14 at 17:38
    
if you find it convenience, and what you looking for is already implemented, you can give a try to CryptoSwift – Marcin Dec 28 '14 at 2:43
1  
Apple just open sourced CommonCrypto. Maybe we can get it running if we have the sources. – eyeballz Nov 4 '15 at 0:55

You can actually build a solution that "just works" (no need to copy a module.modulemap and SWIFT_INCLUDE_PATHS settings over to your project, as required by other solutions here), but it does require you to create a dummy framework/module that you'll import into your framework proper. We can also ensure it works regardless of platform (iphoneos, iphonesimulator, or macosx).

  1. Add a new framework target to your project and name it after the system library, e.g., "CommonCrypto". (You can delete the umbrella header, CommonCrypto.h.)

  2. Add a new Configuration Settings File and name it, e.g., "CommonCrypto.xcconfig". (Don't check any of your targets for inclusion.) Populate it with the following:

    MODULEMAP_FILE[sdk=iphoneos*]        = \
        $(SRCROOT)/CommonCrypto/iphoneos.modulemap
    MODULEMAP_FILE[sdk=iphonesimulator*] = \
        $(SRCROOT)/CommonCrypto/iphonesimulator.modulemap
    MODULEMAP_FILE[sdk=macosx*]          = \
        $(SRCROOT)/CommonCrypto/macosx.modulemap
    
  3. Create the three referenced module map files, above, and populate them with the following:

    • iphoneos.modulemap

      module CommonCrypto [system] {
          header "/Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS.sdk/usr/include/CommonCrypto/CommonCrypto.h"
          export *
      }
      
    • iphonesimulator.modulemap

      module CommonCrypto [system] {
          header "/Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator.sdk/usr/include/CommonCrypto/CommonCrypto.h"
          export *
      }
      
    • macosx.modulemap

      module CommonCrypto [system] {
          header "/Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.11.sdk/usr/include/CommonCrypto/CommonCrypto.h"
          export *
      }
      

    (Replace "Xcode.app" with "Xcode-beta.app" if you're running a beta version. Replace 10.11 with your current OS SDK if not running El Capitan.)

  4. On the Info tab of your project settings, under Configurations, set the Debug and Release configurations of CommonCrypto to CommonCrypto (referencing CommonCrypto.xcconfig).

  5. On your framework target's Build Phases tab, add the CommonCrypto framework to Target Dependencies. Additionally add libcommonCrypto.dylib to the Link Binary With Libraries build phase.

  6. Select CommonCrypto.framework in Products and make sure its Target Membership for your wrapper is set to Optional.

You should now be able to build, run and import CommonCrypto in your wrapper framework.

For an example, see how SQLite.swift uses a dummy sqlite3.framework.

share|improve this answer
3  
Works for me without step (5). With it I get a build error: ld: cannot link directly with /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneS‌​imulator.platform/De‌​veloper/SDKs/iPhoneS‌​imulator8.2.sdk/usr/‌​lib/system/libcommon‌​Crypto.dylib. Link against the umbrella framework 'System.framework' instead. for architecture x86_64 – stannie Mar 27 '15 at 15:14
2  
Excellent! Used this to make github.com/soffes/Crypto I didn't have to link System.framework though. It's worth noting, you have to make a separate wrapper framework for Mac and iOS if your framework is cross platform. – Sam Soffes Apr 21 '15 at 16:42
11  
How or where do people find out stuff like this? – hola Aug 23 '15 at 7:56
3  
this is horrible. I have a zoo of Xcodes each broken in a different ways and having the absolute paths to the headers all over the place is puke invoking. Something is going awfully wrong in cupertino, or at least with whoever is in charge of this modulemap mess – Anton Tropashko Feb 3 at 8:15
2  
7.2.1 rolled out on feb 2nd and release notes says "The Swift compiler is now stricter about including non-modular header files. Debugging a Swift target requires that frameworks be properly modular, meaning all of the publicly-imported headers are either accounted for in the framework's umbrella header, imported from another modular framework, or listed explicitly in a custom module.modulemap file (advanced users only)." this is IMNSHO not for advanced users, this is a feature geared towards true masochists – Anton Tropashko Feb 3 at 8:16
up vote 35 down vote accepted

I found a GitHub project that successfully uses CommonCrypto in a Swift framework: SHA256-Swift. Also, this article about the same problem with sqlite3 was useful.

Based on the above, the steps are:

1) Create a CommonCrypto directory inside the project directory. Within, create a module.map file. The module map will allow us to use the CommonCrypto library as a module within Swift. Its contents are:

module CommonCrypto [system] {
    header "/Applications/Xcode6-Beta5.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator8.0.sdk/usr/include/CommonCrypto/CommonCrypto.h"
    link "CommonCrypto"
    export *
}

2) In Build Settings, within Swift Compiler - Search Paths, add the CommonCrypto directory to Import Paths (SWIFT_INCLUDE_PATHS).

Build Settings

3) Finally, import CommonCrypto inside your Swift files as any other modules. For example:

import CommonCrypto

extension String {

    func hnk_MD5String() -> String {
        if let data = self.dataUsingEncoding(NSUTF8StringEncoding)
        {
            let result = NSMutableData(length: Int(CC_MD5_DIGEST_LENGTH))
            let resultBytes = UnsafeMutablePointer<CUnsignedChar>(result.mutableBytes)
            CC_MD5(data.bytes, CC_LONG(data.length), resultBytes)
            let resultEnumerator = UnsafeBufferPointer<CUnsignedChar>(start: resultBytes, length: result.length)
            let MD5 = NSMutableString()
            for c in resultEnumerator {
                MD5.appendFormat("%02x", c)
            }
            return MD5
        }
        return ""
    }
}

Limitations

Using the custom framework in another project fails at compile time with the error missing required module 'CommonCrypto'. This is because the CommonCrypto module does not appear to be included with the custom framework. A workaround is to repeat step 2 (setting Import Paths) in the project that uses the framework.

The module map is not platform independent (it currently points to a specific platform, the iOS 8 Simulator). I don't know how to make the header path relative to the current platform.

share|improve this answer
16  
Gee, Apple sure want's to make things difficult. Would it kill the Swifties to just let us import files/frameworks without having to go through all this BS? – zaph Sep 5 '14 at 22:22
4  
This is infuriating since the $SDKROOT variable is supposed to allow you platform agnostic paths, but I have no idea how to get to that in Swift. – danimal Oct 2 '14 at 0:29
2  
For me it didn't work until I removed the link "CommonCrypto" from the module.map file. – Teo Sartori Jun 9 '15 at 21:18
1  
Can anyone confirm this working on Xcode 7.3? This solution stopped working for me after the update. – nkukushkin Mar 23 at 10:12
1  
Correnction: it's working fine when I build for simulator, but fails @ linking when I build for an iOS 9.3 device with "ld: library not found for -lCommonCrypto for architecture arm64" – nkukushkin Mar 23 at 11:01

This answer discusses how to make it work inside a framework, and with Cocoapods

modulemap approach

I use modulemap in my wrapper around CommonCrypto https://github.com/onmyway133/CommonCrypto.swift

For those getting header not found, please take a look https://github.com/onmyway133/Arcane/issues/4

  • Make a folder CCommonCrypto containing module.modulemap

      module CCommonCrypto {
        header "/usr/include/CommonCrypto/CommonCrypto.h"
        export *
      }
    
  • Go to Built Settings -> Import Paths

      ${SRCROOT}/Sources/CCommonCrypto
    

Cocoapods with modulemap approach

public header approach

Cocoapods with public header approach

Interesting related posts

share|improve this answer

At the moment, the only real way seems to be implementing the common crypto functionality in objective-c.

share|improve this answer

It's very simple. Add

#import <CommonCrypto/CommonCrypto.h>

to a .h file (the bridging header file of your project). As a convention you can call it YourProjectName-Bridging-Header.h.

Then go to your project Build Settings and look for Swift Compiler - Code Generation. Under it, add the name of your bridging header to the entry "Objetive-C Bridging Header".

You're done. No imports required in your Swift code. Any public Objective-C headers listed in this bridging header file will be visible to Swift.

share|improve this answer
    
your method returns error: using bridging headers with framework targets is unsupported – gorgi93 Mar 7 '15 at 15:46
3  
@gorgi93 You can't use a bridging header in a framework target, as the error suggests. The only option is to put it in the main framework header file, unfortunately. – Charles A. Mar 10 '15 at 23:12
    
If you had actually red the title of this thread you would have seen that the guy is wanting to import the CommonCrypto library into a Swift framework. You cannot use bridging headers in frameworks, and you cannot import the CommonCrypto framework into the umbrella header. – miken.mkndev Mar 11 at 15:51

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.