I am new in iOS development. I am trying to do a simple todo list app. I am using xocde 8 and objective-C language . I tried several tutorial but could not create the database table. Here is my code.
-(void)createOrOpenDB{
printf("createOrOpenDB: into this function \n");
NSArray *docsDir = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *dirPaths = [docsDir objectAtIndex:0];
dbPathString = [[NSString alloc] initWithString: [dirPaths stringByAppendingPathComponent:#"person.db"]];
NSFileManager *fileManager = [NSFileManager defaultManager];
char *err;
printf("createOrOpenDB: into this function before if statement \n");
if(![fileManager fileExistsAtPath:dbPathString]){
const char *dbPath = [dbPathString UTF8String];
printf("createOrOpenDB: into this functions 1st if statement \n");
//create db here
if(sqlite3_open(dbPath, &personDB) ==SQLITE_OK){
const char *sql_stnt = "CREATE TABLE IF NOT EXISTS PERSONS (ID INTEGER PRIMARY KEY AUTOINCREMENT, NAME TEXT, AGE INTEGER)";
if(sqlite3_exec(personDB, sql_stnt, NULL, NULL, &err) !=SQLITE_OK){
printf("Failed to create table\n");
}
sqlite3_close(personDB);
printf("createOrOpenDB: database table created\n");
}
}
}
when i press the add button , its not giving me any error. but its not adding any data. NSLog in not working in xcode 8 . so i did printf instead . and my code breaks before the if statement . can anybody tell me what i am doing wrong?
do like this,
+(DBManager*)getSharedInstance{
if (!sharedInstance) {
sharedInstance = [[super allocWithZone:NULL]init];
[sharedInstance createDB];
}
return sharedInstance;
}
-(BOOL)createDB{
NSString *docsDir;
NSArray *dirPaths;
// Get the documents directory
dirPaths = NSSearchPathForDirectoriesInDomains
(NSDocumentDirectory, NSUserDomainMask, YES);
docsDir = dirPaths[0];
// Build the path to the database file
databasePath = [[NSString alloc] initWithString:
[docsDir stringByAppendingPathComponent: #"student.db"]];
BOOL isSuccess = YES;
NSFileManager *filemgr = [NSFileManager defaultManager];
if ([filemgr fileExistsAtPath: databasePath ] == YES)
{
const char *dbpath = [databasePath UTF8String];
if (sqlite3_open(dbpath, &database) == SQLITE_OK)
{
char *errMsg;
const char *sql_stmt = "create table if not exists studentsDetail (regno integer primary key, name text, department text, year text)";
if (sqlite3_exec(database, sql_stmt, NULL, NULL, &errMsg)
!= SQLITE_OK)
{
isSuccess = NO;
NSLog(#"Failed to create table");
}
else
{
NSLog(#"Table Created Successfully");
}
sqlite3_close(database);
return isSuccess;
}
else {
isSuccess = NO;
NSLog(#"Failed to open/create database");
}
sqlite3_finalize(statement);
}
return isSuccess;
// NSLog(#"database %#", isSuccess);
}
For saving the data in this table,
- (BOOL) saveData:(NSString*)registerNumber name:(NSString*)name
department:(NSString*)department year:(NSString*)year;
{
const char *dbpath = [databasePath UTF8String];
if (sqlite3_open(dbpath, &database) == SQLITE_OK)
{
NSString *insertSQL = [NSString stringWithFormat:#"insert into studentsDetail (regno,name, department, year) values (\"%ld\",\"%#\", \"%#\", \"%#\")",(long)[registerNumber integerValue], name, department, year];
const char *insert_stmt = [insertSQL UTF8String];
sqlite3_prepare_v2(database, insert_stmt,-1, &statement, NULL);
if (sqlite3_step(statement) == SQLITE_DONE)
{
return YES;
}
else {
return NO;
}
sqlite3_reset(statement);
}
return NO;
}
It will create table every time when table does not exist.
Hope t will help you.
Related
I have setup a GlobalVars class to hold my sqlite3 database variable.
static sqlite3** database;
const char *dbPath;
#implementation GlobalVars : NSObject
+(GlobalVars*)sharedInstance {
static GlobalVars *myInstance = nil;
if(myInstance == nil) {
myInstance = [[[self class] alloc] init];
}
return myInstance;
}
+(sqlite3*)getGlobalDatabase {
return &database;
}
+(void)setGlobalDatabase:(sqlite3*)_database {
database = &_database;
}
Then in the header file I have
static sqlite3** database;
which is above the interface. This is how I setup my database variable.
I am then trying to access it when i open the database and prepare it. I can open it, because the open call returns true. I can not prepare it properly, because the statement returns false and it doesn't go into the if statement. I am wondering if I have messed up my pointers, because the prepare statement isn't working, and it doesn't prepare it properly.
-(void)setAllValues:(NSMutableArray*)array {
if(sqlite3_open([GlobalVars getGlobalDBPath], [GlobalVars getGlobalDatabase]) == SQLITE_OK) {
sqlite3_stmt *insertStatement;
NSString *sqlInsert = [NSString stringWithFormat:#"insert into my_table ('_id', 'name', 'age', 'weight', 'height', 'description') VALUES (%i, '%#', '%i', '%i', '%#', '%#')", ID, name, age, weight, height, description];
//*********** This is not opening, and SQLITE_OK is equal to false ***********
if(sqlite3_prepare_v2(([GlobalVars getGlobalDatabase]), [sqlInsert UTF8String], -1, &insertStatement, nil) == SQLITE_OK) {
if(sqlite3_step(insertStatement) == SQLITE_DONE) {
NSLog(#"insert stepping done");
}
sqlite3_reset(insertStatement);
}
sqlite3_finalize(insertStatement);
sqlite3_close([GlobalVars getGlobalDatabase]);
}
}
The variables for the database are all filled with their correct data, and it seems to open the database without issues. When it comes to preparing, it does not work properly and returns false. Any ideas why. Thank you for your assistance, any help is appreciated.
**
You must try this one ... Maybe its help you :
**
#import "DBManager.h"
#import "userRegistrationClass.h"
static DBManager *sharedInstance = nil;
static sqlite3 *database = nil;
static sqlite3_stmt *statement = nil;
#implementation DBManager
#pragma mark
#pragma mark Get shared Function
+(DBManager*)getSharedInstance{
if (!sharedInstance) {
sharedInstance = [[super allocWithZone:NULL]init];
[sharedInstance createDB];
}
return sharedInstance;
}
#pragma mark
#pragma mark Create DataBase
-(BOOL)createDB{
NSString *docsDir;
NSArray *dirPaths;
// Get the documents directory
// http://www.mycashkit.com/my-earnings.php
dirPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSLog(#"Dir Path Value is %#",dirPaths);
docsDir = [dirPaths objectAtIndex:0];
NSLog(#"DocsDir Path Value is %#",docsDir);
// Build the path to the database file
databasePath = [[NSString alloc] initWithString:[docsDir stringByAppendingPathComponent: #"UserRegInfo.sqlite"]];
NSLog(#"Data base Work's %#:",databasePath);
BOOL isSuccess = YES;
NSFileManager *filemgr = [NSFileManager defaultManager];
// NSString *currentPath = [filemgr currentDirectoryPath];
NSLog(#"My file managaer value is %#",filemgr);
//NSLog(#"My current drictory path is %#",currentPath);
//the file will not be there when we load the application for the first time
//so this will create the database table
if ([filemgr fileExistsAtPath: databasePath ] == NO)
{
const char *dbpath = [databasePath UTF8String];
NSLog(#"Constan charcter value is %s:-",dbpath);
if (sqlite3_open(dbpath, &database) == SQLITE_OK)
{
char *errMsg;
const char *sql_stmt = "create table if not exists UserInfo(UserID integer primary key, UserName,Gender,UserEmailID,Password,RePassword,DOB, MobileNo,IsUserType)";
const char *sql_stmt2 = "create table if not exists TestInfo(TestID integer primary key, TestName,TestType)";
// NSString *dbPathFromApp=[[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:#"UserRegInfo.sqlite"];[filemgr copyItemAtPath:dbPathFromApp toPath:databasePath error:nil];
NSLog(#"Constan charcter value is %s:-",dbpath);
if (sqlite3_exec(database, sql_stmt, NULL, NULL, &errMsg) && (sqlite3_exec(database, sql_stmt2, NULL, NULL, &errMsg)!= SQLITE_OK))
{
isSuccess = NO;
NSLog(#"Failed to create table");
}
NSLog(#"Print Sqlite%d",(sqlite3_exec(database, sql_stmt, NULL, NULL, &errMsg)));
sqlite3_close(database);
return isSuccess;
}
else {
isSuccess = NO;
NSLog(#"Failed to open/create database");
}
}
return isSuccess;
}
#pragma mark
#pragma mark Save Data Function
-(BOOL)saveData:(NSString*)insertSQL{
const char *dbpath = [databasePath UTF8String];
if (sqlite3_open(dbpath, &database) == SQLITE_OK)
{
NSLog(#" my Sqlite Query is :- %#",insertSQL);
const char *insert_stmt = [insertSQL UTF8String];
sqlite3_prepare_v2(database, insert_stmt,-1, &statement, NULL);
if (sqlite3_step(statement) == SQLITE_DONE)
{
return YES;
}
else
{
NSLog(#"Squlite Error Msg is %s",sqlite3_errmsg(database));
return NO;
}
}
return NO;
}
I want to insert text in my sqlite table ,it contains large amount(around 1000 charecters)
Here is my code
//create function
//createdb here
if (sqlite3_open([dbPathString UTF8String], &database)==SQLITE_OK) {
const char *sql_stmt="CREATE TABLE IF NOT EXISTS mytablename(description TEXT)";
sqlite3_exec(database, sql_stmt, NULL, NULL, &error);
sqlite3_close(database);
}
//inserting
for (int i=0; i<_generalContentArray.count; i++)
{
char *error;
if (sqlite3_open([dbPathString UTF8String], &database)==SQLITE_OK)
{
NSString *query=[NSString stringWithFormat:#"INSERT INTO mytablename(description) values('%#')",[[_generalContentArray objectAtIndex:i]objectForKey:#"description"]];
const char *insert_stmt=[query UTF8String];
if (sqlite3_exec(database, insert_stmt, NULL, NULL, &error )==SQLITE_OK)
{
NSLog(#"Text added");
}
else
{
NSLog(#"Text not added");
}
sqlite3_close(database);
}
}
My problem is it never execute SQLITE_OK statement and always goes to else statement,text is not adding to my table,Please help
you have to check db is existing or not.try this...
for (int i=0; i<_generalContentArray.count; i++)
{
char *error;
//you need to check db is exising or not
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *databasePath = [documentsDirectory stringByAppendingPathComponent:#"your db name"];
if (sqlite3_open([databasePath UTF8String], &database)==SQLITE_OK)
{
NSString *query=[NSString stringWithFormat:#"INSERT INTO mytablename(description) values('%#')",[[_generalContentArray objectAtIndex:i]objectForKey:#"description"]];
const char *insert_stmt=[query UTF8String];
if (sqlite3_exec(database, insert_stmt, NULL, NULL, &error )==SQLITE_OK)
{
NSLog(#"Text added");
}
else
{
NSLog(#"Text not added");
}
sqlite3_close(database);
}
}
change your query like this...
NSString *query=[NSString stringWithFormat:#"INSERT INTO mytablename('description') VALUES('%#')",[[_generalContentArray objectAtIndex:i]objectForKey:#"description"]];
I have an app where I take details of the user and save it to SQLite db. Also I am able to find the details and display the result.
-(void) createDB{
NSString *docsDir;
NSArray *dirPaths;
// Get the documents directory
dirPaths = NSSearchPathForDirectoriesInDomains(
NSDocumentDirectory, NSUserDomainMask, YES);
docsDir = dirPaths[0];
// Build the path to the database file
_databasePath = [[NSString alloc]
initWithString: [docsDir stringByAppendingPathComponent:
#"contactUnique6.db"]];
NSFileManager *filemgr = [NSFileManager defaultManager];
if ([filemgr fileExistsAtPath: _databasePath ] == NO)
{
const char *dbpath = [_databasePath UTF8String];
if (sqlite3_open(dbpath, &_contactDB) == SQLITE_OK)
{
char *errMsg;
const char *sql_stmt =
"CREATE TABLE IF NOT EXISTS CONTACTS (ID INTEGER PRIMARY KEY AUTOINCREMENT , NAME TEXT , ADDRESS TEXT, PHONE TEXT )";
if (sqlite3_exec(_contactDB, sql_stmt, NULL, NULL, &errMsg) != SQLITE_OK)
{
_status.text = #"Failed to create table";
}
sqlite3_close(_contactDB);
} else {
_status.text = #"Failed to open/create database";
}
}
- (IBAction)saveData:(id)sender {
sqlite3_stmt *statement;
const char *dbpath = [_databasePath UTF8String];
if (sqlite3_open(dbpath, &_contactDB) == SQLITE_OK)
{
NSString *insertSQL = [NSString stringWithFormat:
#"INSERT OR IGNORE INTO CONTACTS (name, address, phone) VALUES (\"%#\", \"%#\", \"%#\")",
_name.text, _address.text, _phone.text];
const char *insert_stmt = [insertSQL UTF8String];
sqlite3_prepare_v2(_contactDB, insert_stmt,
-1, &statement, NULL);
if (sqlite3_step(statement) == SQLITE_DONE)
{
_status.text = #"Contact added";
_name.text = #"";
_address.text = #"";
_phone.text = #"";
} else {
_status.text = #"Failed to add contact";
}
sqlite3_finalize(statement);
sqlite3_close(_contactDB);
}
}
- (IBAction)findContact:(id)sender {
const char *dbpath = [_databasePath UTF8String];
sqlite3_stmt *statement;
if (sqlite3_open(dbpath, &_contactDB) == SQLITE_OK)
{
NSString *querySQL = [NSString stringWithFormat:
#"SELECT address, phone FROM contacts WHERE name=\"%#\"",
_name.text];
const char *query_stmt = [querySQL UTF8String];
if (sqlite3_prepare_v2(_contactDB,
query_stmt, -1, &statement, NULL) == SQLITE_OK)
{
if (sqlite3_step(statement) == SQLITE_ROW)
{
NSString *addressField = [[NSString alloc]
initWithUTF8String:
(const char *) sqlite3_column_text(
statement, 0)];
_address.text = addressField;
NSString *phoneField = [[NSString alloc]
initWithUTF8String:(const char *)
sqlite3_column_text(statement, 1)];
_phone.text = phoneField;
_status.text = #"Match found";
} else {
_status.text = #"Match not found";
_address.text = #"";
_phone.text = #"";
}
sqlite3_finalize(statement);
}
sqlite3_close(_contactDB);
}
}
The above code is working good. However when I am trying to use an update, it is not displaying when I try to find it. It gives me a match not found even though the contact was saved.
This is the code by which I am trying to update:
- (IBAction)saveData:(id)sender {
sqlite3_stmt *statement;
const char *dbpath = [_databasePath UTF8String];
if (sqlite3_open(dbpath, &_contactDB) == SQLITE_OK)
{
NSString *insertSQL = [NSString stringWithFormat:
#"INSERT OR IGNORE INTO CONTACTS (name, address, phone) VALUES (\"%#\", \"%#\", \"%#\")",
_name.text, _address.text, _phone.text];
insertSQL = [NSString stringWithFormat:
#"UPDATE CONTACTS SET name=\"%#\", address=\"%#\", phone=\"%#\"",
_name.text, _address.text, _phone.text];
const char *insert_stmt = [insertSQL UTF8String];
sqlite3_prepare_v2(_contactDB, insert_stmt,
-1, &statement, NULL);
if (sqlite3_step(statement) == SQLITE_DONE)
{
_status.text = #"Contact added";
_name.text = #"";
_address.text = #"";
_phone.text = #"";
} else {
_status.text = #"Failed to add contact";
}
sqlite3_finalize(statement);
sqlite3_close(_contactDB);
}
}
Basically my aim is to be able to save-update-find. (without losing the primary key on update, as I have FK relations)
EDIT
This is my create db method
-(void) createDB{
NSString *docsDir;
NSArray *dirPaths;
// Get the documents directory
dirPaths = NSSearchPathForDirectoriesInDomains(
NSDocumentDirectory, NSUserDomainMask, YES);
docsDir = dirPaths[0];
// Build the path to the database file
_databasePath = [[NSString alloc]
initWithString: [docsDir stringByAppendingPathComponent:
#"contactUnique6.db"]];
NSFileManager *filemgr = [NSFileManager defaultManager];
if ([filemgr fileExistsAtPath: _databasePath ] == NO)
{
const char *dbpath = [_databasePath UTF8String];
if (sqlite3_open(dbpath, &_contactDB) == SQLITE_OK)
{
char *errMsg;
const char *sql_stmt =
"CREATE TABLE IF NOT EXISTS CONTACTS (ID INTEGER PRIMARY KEY AUTOINCREMENT , NAME TEXT , ADDRESS TEXT, PHONE TEXT )";
if (sqlite3_exec(_contactDB, sql_stmt, NULL, NULL, &errMsg) != SQLITE_OK)
{
_status.text = #"Failed to create table";
}
sqlite3_close(_contactDB);
} else {
_status.text = #"Failed to open/create database";
}
}
i cant get your second -(IBAction)saveData:(id)sender {} method [ Third code block ]..
You said above 2 blocks are working properly so its ok.
i think you embedded the update's logic in insert's logic i.e. you embedded the update method in your saveData method..
Here i cant get what u have done, so instead of code here i m providing the template for update query, just put your code in it...
sqlite3_stmt *statement;
if(sqlite3_open(dbpath, &database_object) == SQLITE_OK)
{
NSString *sql = [NSString stringWithFormat:#"update table_name set column_name = \"%#\"", Your_value];
const char *sql_stmt = [sql UTF8String];
if(sqlite3_prepare_v2(database_object , sql_stmt, -1, &statement, NULL) != SQLITE_OK)
NSLog(#"Error while creating update statement. '%s'", sqlite3_errmsg(database_object));
if(SQLITE_DONE != sqlite3_step(statement))
NSLog(#"Error while updating. '%s'", sqlite3_errmsg(database_object));
sqlite3_finalize(statement);
}
Go with this template, i think it will work for you...
I am having tabbed iPhone application.In the first tab I created sqlite table and inserted values to the table,these are done successfully.In the second tab I am able to get the values from table but in third class when I am executing the select query, I am getting the no such table exception.
Even I deleted the app from simulator and cleaned the project,but I got the same problem.
Kindly give me solutions.
Coding for create and insert:
-(void)InsertLoginDetails:(NSString *)user fun:(NSString *)pwd{
sqlite3_stmt *statement;
const char *dbpath = [_databasePath UTF8String];
if (sqlite3_open(dbpath, &_contactDB) == SQLITE_OK)
{
NSString *insertSQL = [NSString stringWithFormat:
#"INSERT INTO Login ( USERNAME, PASSWORD) VALUES (\"%#\", \"%#\")",
user, pwd];
const char *insert_stmt = [insertSQL UTF8String];
sqlite3_prepare_v2(_contactDB, insert_stmt,
-1, &statement, NULL);
if (sqlite3_step(statement) == SQLITE_DONE)
{
NSLog(#"Inserted");
} else {
NSLog(#"Failed to insert");
}
sqlite3_finalize(statement);
sqlite3_close(_contactDB);
}
}
-(void)createLoginTable{
NSString *docsDir;
NSArray *dirPaths;
// Get the documents directory
dirPaths = NSSearchPathForDirectoriesInDomains(
NSDocumentDirectory, NSUserDomainMask, YES);
docsDir = dirPaths[0];
// Build the path to the database file
_databasePath = [[NSString alloc]
initWithString: [docsDir stringByAppendingPathComponent:
#"login.db"]];
NSFileManager *filemgr = [NSFileManager defaultManager];
if ([filemgr fileExistsAtPath: _databasePath ] == NO)
{
const char *dbpath = [_databasePath UTF8String];
if (sqlite3_open(dbpath, &_contactDB) == SQLITE_OK)
{
char *errMsg;
const char *sql_stmt =
"CREATE TABLE IF NOT EXISTS Login (ID INTEGER PRIMARY KEY AUTOINCREMENT, USERNAME TEXT, PASSWORD TEXT)";
if (sqlite3_exec(_contactDB, sql_stmt, NULL, NULL, &errMsg) != SQLITE_OK)
{
NSLog(#"Failed to create table");
}
sqlite3_close(_contactDB);
NSLog(#"Table created");
} else {
NSLog(#"Failed to open/create database");
}
}
}
Code for getting values:
-(void)checkLoginSession{
///////////////GET DB DATAS///////////////////////
const char *dbpath = [_databasePath UTF8String];
sqlite3_stmt *statement;
if (sqlite3_open(dbpath, &_contactDB) == SQLITE_OK)
{
NSString *querySQL = #"SELECT USERNAME, PASSWORD FROM Login";
const char *query_stmt = [querySQL UTF8String];
if (sqlite3_prepare_v2(_contactDB,
query_stmt, -1, &statement, NULL) == SQLITE_OK)
{
if (sqlite3_step(statement) == SQLITE_ROW)
{
strDBUsername = [[NSString alloc]
initWithUTF8String:
(const char *) sqlite3_column_text(
statement, 0)];
strDBPwd = [[NSString alloc]
initWithUTF8String:(const char *)
sqlite3_column_text(statement, 1)];
NSLog(#"Settings page Login Details %# %#", strDBUsername , strDBPwd );
// _address.text = addressField;
//
// _phone.text = phoneField;
// _status.text = #"Match found";
} else {
// _status.text = #"Match not found";
// _address.text = #"";
// _phone.text = #"";
}
sqlite3_finalize(statement);
}
else{
NSLog(#"SQLITE NOT OK");
NSLog(#"Error %s ", sqlite3_errmsg(_contactDB));
}
sqlite3_close(_contactDB);
}
I just start develop an ios app just like Contact.
It include Name, Birthday, Group(School, Work), BloodType, Image.. etc.
In that, other Data can insert by typing.
But, image can come from taking photo, download from facebook.. etc.
Input images into xcode is impossible. Bcoz, another images can come again and again.
How should i do? Please, advice me.
you just ADD libSqlite3.dylib to Linked FrameWork and Lilbraries and declared database varibles in .h file
//Database Variables
#property (strong, nonatomic) NSString *databasePath;
#property (nonatomic)sqlite3 *contactDB;
drag and drop UIImageView and name to that... i declared as imgView.
Goto .m file you just copy and paste that code
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
NSString *docsDir;
NSArray *dirPaths;
// Get the documents directory
dirPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
docsDir = dirPaths[0];
// Build the path to the database file
_databasePath = [[NSString alloc] initWithString: [docsDir stringByAppendingPathComponent: #"images.db"]];
//docsDir NSPathStore2 * #"/Users/gayathiridevi/Library/Application Support/iPhone Simulator/7.0.3/Applications/B5D4D2AF-C613-45F1-B414-829F38344C2A/Documents" 0x0895e160
NSFileManager *filemgr = [NSFileManager defaultManager];
if ([filemgr fileExistsAtPath: _databasePath ] == NO)
{
const char *dbpath = [_databasePath UTF8String];
if (sqlite3_open(dbpath, &_contactDB) == SQLITE_OK)
{
char *errMsg;
const char *sql_stmt = "CREATE TABLE IF NOT EXISTS IMAGETB (ID INTEGER PRIMARY KEY AUTOINCREMENT,URL TEXT UNIQUE, IMAGE BLOB)";
if (sqlite3_exec(_contactDB, sql_stmt, NULL, NULL, &errMsg) != SQLITE_OK)
{
NSLog( #"User table Not Created Error: %s", errMsg);
}
else
{
NSLog( #"User table Created: ");
}
sqlite3_close(_contactDB);
}
else {
NSLog( #"DB Not Created");
}
}
[self saveImage];
[self showImage];
}
- (void)saveImage
{
sqlite3_stmt *statement;
const char *dbpath = [_databasePath UTF8String];
if (sqlite3_open(dbpath, &_contactDB) == SQLITE_OK)
{
NSString *insertSQL=#"INSERT INTO IMAGETB(image) VALUES(?)";
if(sqlite3_prepare_v2(_contactDB, [insertSQL cStringUsingEncoding:NSUTF8StringEncoding], -1, &statement, NULL)== SQLITE_OK)
{
UIImage *image = [[UIImage alloc] initWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:#"https://lh6.googleusercontent.com/-vJBBGUtpXxk/AAAAAAAAAAI/AAAAAAAAADQ/nfgVPX1n-Q8/photo.jpg"]]];
NSData *imageData=UIImagePNGRepresentation(image);
//sqlite3_bind_text(statement, 1, [#"" UTF8String], -1, SQLITE_TRANSIENT);
sqlite3_bind_blob(statement, 1, [imageData bytes], [imageData length], SQLITE_TRANSIENT);
NSLog(#"Length : %lu", (unsigned long)[imageData length]);
}
if (sqlite3_step(statement) == SQLITE_DONE)
{
NSLog( #"Insert into row id %lld",(sqlite3_last_insert_rowid(_contactDB)));
}
else {
NSLog( #"Error IN INSERT" );
}
sqlite3_finalize(statement);
sqlite3_close(_contactDB);
}
}
- (void)showImage
{
sqlite3_stmt *statement;
const char *dbpath = [_databasePath UTF8String];
int i = 1;
if(sqlite3_open(dbpath,&_contactDB)==SQLITE_OK)
{
NSString *insertSQL = [NSString stringWithFormat:#"Select IMAGE FROM IMAGETB WHERE ID = %d",i];
if(sqlite3_prepare_v2(_contactDB,[insertSQL cStringUsingEncoding:NSUTF8StringEncoding], -1, &statement, NULL) == SQLITE_OK) {
while(sqlite3_step(statement) == SQLITE_ROW) {
int length = sqlite3_column_bytes(statement, 0);
NSData *imageData = [NSData dataWithBytes:sqlite3_column_blob(statement, 0) length:length];
NSLog(#"Length : %lu", (unsigned long)[imageData length]);
if(imageData == nil)
NSLog(#"No image found.");
else
_imgView.image = [UIImage imageWithData:imageData];
NSLog(#"image found.");
}
}
sqlite3_finalize(statement);
}
sqlite3_close(_contactDB);
}
Its my code. You fix back and Forward Button to get details by changing that i value in
-(void)showImage
function
Regarding taking photos or grabbing from your library, see UIImagePickerController Class Reference and the Camera Programming Topics for iOS. For grabbing photos from Facebook, you should refer to its API, as that's a whole different kettle of fish.