· 8 years ago · Feb 21, 2018, 03:38 PM
1#import <UIKit/UIKit.h>
2#import <sqlite3.h>
3
4@interface ViewController : UIViewController
5
6@property (nonatomic, strong) NSString *databasePath;
7@property (nonatomic) sqlite3 *particularsDB;
8@property (weak, nonatomic) IBOutlet UITextField *name;
9@property (weak, nonatomic) IBOutlet UITextField *password;
10
11- (IBAction)saveData:(id)sender;
12@property (weak, nonatomic) IBOutlet UILabel *status;
13
14
15
16@end
17
18#import "ViewController.h"
19
20@interface ViewController ()
21
22@end
23
24@implementation ViewController
25
26- (void)viewDidLoad {
27[super viewDidLoad];
28NSString *docsDir;
29NSArray *dirPaths;
30// Get the documents directory
31dirPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,
32NSUserDomainMask, YES);
33docsDir = dirPaths[0];
34
35// Build the path to the database file
36
37
38_databasePath = [[NSString alloc]
39 initWithString: [docsDir stringByAppendingPathComponent:
40 @"particulars.db"]];
41NSFileManager *filemgr = [NSFileManager defaultManager];
42
43
44if ([filemgr fileExistsAtPath: _databasePath ] == NO)
45{
46
47const char *dbpath = [_databasePath UTF8String];
48
49
50if (sqlite3_open(dbpath, &_particularsDB) == SQLITE_OK)
51{
52 char *errMsg;
53 const char *sql_stmt = "CREATE TABLE IF NOT EXISTS CONTACTS (username,
54password)";
55 if (sqlite3_exec(_particularsDB, sql_stmt, NULL, NULL, &errMsg) !=
56SQLITE_OK) {
57 _status.text = @"Failed to create table"; }
58 sqlite3_close(_particularsDB); }
59else
60{
61 _status.text = @"Failed to open/create database";
62
63}
64}
65}
66
67
68
69- (void)didReceiveMemoryWarning {
70[super didReceiveMemoryWarning];
71// Dispose of any resources that can be recreated.
72}
73
74
75- (IBAction)saveData:(id)sender {
76
77sqlite3_stmt *statement;
78const char *dbpath = [_databasePath UTF8String];
79NSLog(@"%s", dbpath );
80if (sqlite3_open(dbpath, &_particularsDB) == SQLITE_OK)
81{
82 NSString *insertSQL = [NSString stringWithFormat:
83 @"INSERT INTO CONTACTS (username, password)
84VALUES ("%@","%@")", _name.text, _password.text];
85 const char *insert_stmt = [insertSQL UTF8String];
86 sqlite3_prepare_v2(_particularsDB, insert_stmt, -1, &statement, NULL);
87
88 if (sqlite3_step(statement) == SQLITE_DONE)
89 {
90 _status.text = @"Registration success";
91 _name.text = @"";
92 _password.text = @"";
93 }
94 else
95 {
96
97 _status.text = @"Failed to register";
98 }
99 sqlite3_finalize(statement);
100 sqlite3_close(_particularsDB);
101 }
102
103
104}
105@end