-
(void)viewDidLoad { [super viewDidLoad]; [self createDB]; }
-(void)createDB { NSArray *path = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); NSString *docdir = [path objectAtIndex:0]; //path[0]; dbpath = [docdir stringByAppendingPathComponent:@"arun.sqlite"]; NSLog(@"database path : %@",dbpath); NSFileManager *filemgr = [NSFileManager defaultManager]; if ([filemgr fileExistsAtPath:dbpath] == NO) { //OPEN AND CREATE DATABASE if (sqlite3_open([dbpath UTF8String], &myDB) == SQLITE_OK) { //CREATE TABLE NSString *createSQL = @"CREATE TABLE IF NOT EXISTS STUDENT (ID INTEGER PRIMARY KEY AUTOINCREMENT, NAME TEXT, ADDRESS TEXT, ROLLNO INTEGER,IMAGE BLOB)"; char *error = nil; if (sqlite3_exec(myDB, [createSQL UTF8String] , NULL, NULL, &error) == SQLITE_OK) { NSLog(@"Database and tables created."); } else { NSLog(@"Error %s",error); } sqlite3_close(myDB); } } } - (void)saveImage { sqlite3_stmt *compiledStmt; sqlite3 *db; if(sqlite3_open([dbpath UTF8String], &db)==SQLITE_OK) { NSString *insertSQL = [NSString stringWithFormat:@"INSERT INTO STUDENT (ROLLNO,IMAGE) VALUES(\"%@\", \"%@\")", rollnoTxt.text, selectImgvw.image]; if(sqlite3_prepare_v2(db,[insertSQL cStringUsingEncoding:NSUTF8StringEncoding], -1, &compiledStmt, NULL) == SQLITE_OK){ UIImage *image = selectImgvw.image; NSData *imgdata = UIImagePNGRepresentation(image); sqlite3_bind_blob(compiledStmt, 1, [imgdata bytes], (int)[imgdata length], SQLITE_TRANSIENT); if(sqlite3_step(compiledStmt) != SQLITE_DONE ) { NSLog( @"Error: %s", sqlite3_errmsg(db) ); } else { NSLog( @"Insert into row id = %lld", (sqlite3_last_insert_rowid(db))); } sqlite3_finalize(compiledStmt); } } sqlite3_close(db); } - (void)showImage { sqlite3_stmt *compiledStmt; sqlite3 *db; if(sqlite3_open([dbpath UTF8String], &db)==SQLITE_OK){ NSString *insertSQL = [NSString stringWithFormat:@"SELECT IMAGE FROM STUDENT WHERE ROLLNO = %@",rollnoTxt.text]; if(sqlite3_prepare_v2(db,[insertSQL cStringUsingEncoding:NSUTF8StringEncoding], -1, &compiledStmt, NULL) == SQLITE_OK) { while(sqlite3_step(compiledStmt) == SQLITE_ROW) { int length = sqlite3_column_bytes(compiledStmt, 0); NSData *imgdata = [NSData dataWithBytes:sqlite3_column_blob(compiledStmt, 0) length:length]; NSLog(@"Length : %ld", [imgdata length]); if(imgdata == nil) NSLog(@"No image found."); else { UIImage *img = [UIImage imageWithData:imgdata]; displayImgvw.image = img; } } } sqlite3_finalize(compiledStmt); } sqlite3_close(db); }
Above is my code snippet. Image is saving in Sqlite database but problem is while fetching the image,I am not getting any value when feed to image view. I have been doing for a while. Did more R&D but could not solve. Please suggest me if anyone can make this Thanks for advance help
Aucun commentaire:
Enregistrer un commentaire