官方集成文档:https://www.zetetic.net/sqlcipher/ios-tutorial/
从GitHub下载 SQLCipher到本地: https://github.com/sqlcipher/sqlcipher
1> 选择你的项目,右键,选择 "Add Files to [你的工程]";在弹出的选择窗口找到你刚才从git下载的sqlcipher路径,打开sqlcipher文件夹,选择sqlcipher.xcodeproj
2> 点击工程,选择TARGETS中你的工程,点击 Build Phases Tab栏,展开 Target Dependencies 点击 +
3> 添加 sqlcipher 静态库
4> 展开Link Binary With Libraries
5> 添加+libsqlcipher.a库
注:如果你的工程库中已经添加了 libsqlite3.dylib 或者其他的SQLite库,请Remove掉,否则可能会提示出现重复sqlite库
6> 回到你的工程编辑面板,选择工程,TARGETS 你的工程Target, Build Settings Tab栏,选择 Header Search Paths 项,双击键入新值: ./sqlcipher/src
7> 选择 Other C Flags ,双击 添加 -DSQLITE_HAS_CODEC
注:Release 和 Debug的配置值一样
现在就可以直接使用 sqlite3 加密数据库
如代码:
#import "AppDelegate.h"
#import
@interface AppDelegate ()
@property (nonatomic) BOOL isLoginViewControllerDisplayed;
@property (readonly) NSURL *databaseURL;
@property (readonly) BOOL databaseExists;
@end
@implementation AppDelegate
@dynamic databaseURL;
@dynamic databaseExists;
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
// Override point for customization after application launch.
// Set up a SQLCipher database connection:
sqlite3 *db;
if (sqlite3_open([[self.databaseURL path] UTF8String], &db) == SQLITE_OK)
{
const char* key = [@"StrongPassword" UTF8String];
sqlite3_key(db, key, (int)strlen(key));
if (sqlite3_exec(db, (const char*) "SELECT count(*) FROM sqlite_master;", NULL, NULL, NULL) == SQLITE_OK)
{
NSLog(@"Password is correct, or a new database has been initialized");
}
else
{
NSLog(@"Incorrect password!");
}
sqlite3_close(db);
}
return YES;
}
- (NSURL *)databaseURL
{
NSArray *URLs = [[NSFileManager defaultManager] URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask];
NSURL *directoryURL = [URLs firstObject];
NSURL *databaseURL = [directoryURL URLByAppendingPathComponent:@"secure.db"];
return databaseURL;
}
- (BOOL)databaseExists
{
BOOL exists = NO;
NSError *error = nil;
exists = [[self databaseURL] checkResourceIsReachableAndReturnError:&error];
if (exists == NO && error != nil)
{
NSLog(@"Error checking availability of database file: %@", error);
}
return exists;
}
@end
运行工程出现,如下日志表示运行成功