Swift中使用MD5的正确姿势
在Swift4.0中,无法直接#import CommonCtypto,所以需要桥接OC的CommonCtypto。但是我发现XCode9系统不会自动创建BridgeHeader文件,所以正确的姿势是这样的:
在项目中创建文件夹
CommonCtypto在文件夹中新建
module.modulemap文件和CommonCryptoHeader.h文件在
.modulemap文件中添加代码:1
2
3
4
5module CommonCrypto [system] {
header "/Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS.sdk/usr/include/CommonCrypto/CommonCrypto.h"
header "/Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS.sdk/usr/include/CommonCrypto/CommonRandom.h"
export *
}在CommonCryptoHeader.h中导入CommonCrypto:
1
#include <CommonCrypto/CommonCrypto.h>
在
targets——Build Setting中找到Swift Compiler-Search Paths,在其Import Paths中添加CommCrypto文件夹的路径:$(SRCROOT)/ProjectName/CommonCrypt。在写MD5的文件里
import CommonCrypto即可。
MD5加密的Swift正确写法:
1 | func md5String() ->String!{ |
更新:
在Swift4.2中,不能再使用上述方法导入CommonCrypto了,因为Swift4.2可以直接 import CommonCrypto 。
所以更新到Swift4.2后,需要将上面生成的module.modulemap和CommonCryptoHeader.h两个文件删掉,import Paths里的路径也删掉,在创建MD5时import CommonCrypto 就可以了。