我发现了一个GitHub项目,成功地在Swift框架中使用了CommonCrypto:SHA256-Swift。此外,这篇文章关于使用sqlite3遇到的同样问题也很有用。
基于上述内容,步骤如下:
1)在项目目录中创建一个名为CommonCrypto
的文件夹,在其中创建一个module.map
文件,这个文件将允许我们在Swift中将CommonCrypto库作为模块使用。它的内容如下:
module CommonCrypto [system] {
header "/Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator8.0.sdk/usr/include/CommonCrypto/CommonCrypto.h"
link "CommonCrypto"
export *
}
2) 在“Build Settings”中的Swift Compiler - Search Paths中,将CommonCrypto
目录添加到Import Paths(SWIFT_INCLUDE_PATHS
)。
3) 最后,在您的Swift文件中像导入其他模块一样导入CommonCrypto。例如:
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 ""
}
}
限制
在另一个项目中使用自定义框架会在编译时失败,出现错误消息missing required module 'CommonCrypto'
。这是因为自定义框架中未包含CommonCrypto模块。解决方法是在使用该框架的项目中重复步骤2(设置导入路径
)。
模块映射不具备平台独立性(它当前指向特定平台,即iOS 8模拟器)。我不知道如何使头文件路径相对于当前平台。
iOS 8及以下版本的更新:我们应该删除行link "CommonCrypto",以获得成功的编译结果。
更新/编辑
我一直收到以下构建错误:
ld: library not found for -lCommonCrypto for architecture x86_64
clang: error: linker command failed with exit code 1 (use -v to see invocation)
除非从我创建的module.map
文件中删除link "CommonCrypto"
这一行,否则会一直出现此错误。一旦我删除了这一行,就成功构建了。