i have an application in which i have 2 pages.one page is Register page and other is Login Page .
when a new user enter values in the register page and click on the submit the values are initially submitted to the server database.
When the same user come backs to the login page and enters his username and password and clicks on the submit button i get a JSON response on the console which returns the
{"TokenID":"fuUsat27to","isError":false,"ErrorMessage":"","Result":[{"UserId":"164","FirstName":"Indu","LastName":"nair","Email":"indu#itg.com","ProfileImage":null,"ThumbnailImage":null,"DeviceInfoId":"22"}],"ErrorCode":900}
tokenID,USerID and DeviceID for every user and which are different for every user.
when the submit button is pressed on the login page all the values are saved in sqlite database.
In my login page i have 2 function first function checks that if user enter username and password and click on the submit button,the values should come from server if value is present in server .
If value is present in server database then it will take value from server and put all data in sqlite database.
This is all first time process for a new user.After all this happens the next function should be called.
In this function work is only to check username and password present in sqlite database .
If username and password is present then open the page otherwise show an error message.
-(void)check
{
app.journeyList = [[NSMutableArray alloc]init];
[self createEditableCopyOfDatabaseIfNeeded];
NSString *filePath = [self getWritableDBPath];
sqlite3 *database;
if(sqlite3_open([filePath UTF8String], &database) == SQLITE_OK) {
const char *sqlStatement = "SELECT Username,Password FROM UserInformation where Username=? and Password=?";
sqlite3_stmt *compiledStatement;
if(sqlite3_prepare_v2(database, sqlStatement, -1, &compiledStatement, NULL) == SQLITE_OK) {
sqlite3_bind_text(compiledStatement, 1, [Uname.text UTF8String], -1, SQLITE_TRANSIENT);
sqlite3_bind_text(compiledStatement, 2, [Password.text UTF8String], -1, SQLITE_TRANSIENT);
//NSString *loginname= [NSString stringWithUTF8String:(char *)sqlite3_column_text(compiledStatement, 1)];
// NSString *loginPassword = [NSString stringWithUTF8String:(char *)sqlite3_column_text(compiledStatement, 2)];
}
if(sqlite3_step(compiledStatement) != SQLITE_ROW ) {
//NSLog( #"Save Error: %s", sqlite3_errmsg(database) );
UIAlertView *alert = [[UIAlertView alloc]initWithTitle:#"UIAlertView" message:#"User is not valid" delegate:self cancelButtonTitle:#"OK" otherButtonTitles:nil];
[alert show];
[alert release];
alert = nil;
}
else {
isUserValid = YES;
if (isUserValid) {
app = (JourneyAppDelegate *)[[UIApplication sharedApplication]delegate];
TTabBar *tabbar=[[TTabBar alloc] init];
[app.navigationController pushViewController:tabbar animated:YES];
tabbar.selectedIndex = 0;
}
}
sqlite3_finalize(compiledStatement);
}
sqlite3_close(database);
}
//this is used when the user first time log in the server and sends
-(void)sendRequest
{
UIDevice *device = [UIDevice currentDevice];
NSString *udid = [device uniqueIdentifier];
NSString *sysname = [device systemName];
NSString *sysver = [device systemVersion];
NSString *model = [device model];
NSLog(#"idis:%#",[device uniqueIdentifier]);
NSLog(#"system nameis :%#",[device systemName]);
NSLog(#"System version is:%#",[device systemVersion]);
NSLog(#"System model is:%#",[device model]);
NSLog(#"device orientation is:%d",[device orientation]);
NSString *post = [NSString stringWithFormat:#"Loginkey=%#&Password=%#&DeviceCode=%#&Firmware=%#&IMEI=%#",Uname.text,Password.text,model,sysver,udid];
NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSString *postLength = [NSString stringWithFormat:#"%d", [postData length]];
NSLog(#"%#",postLength);
NSMutableURLRequest *request = [[[NSMutableURLRequest alloc] init] autorelease];
[request setURL:[NSURL URLWithString:#"http://192.168.0.1:96/JourneyMapperAPI?RequestType=Login"]];
[request setHTTPMethod:#"POST"];
[request setValue:postLength forHTTPHeaderField:#"Content-Length"];
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
[request setHTTPBody:postData];
NSURLConnection *theConnection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
if (theConnection) {
webData = [[NSMutableData data] retain];
NSLog(#"%#",webData);
}
else
{
}
}
-(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
[webData setLength: 0];
}
-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
[webData appendData:data];
}
-(void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
[connection release];
[webData release];
}
-(void)connectionDidFinishLoading:(NSURLConnection *)connection
{
NSString *loginStatus = [[NSString alloc] initWithBytes: [webData mutableBytes] length:[webData length] encoding:NSUTF8StringEncoding];
NSLog(#"%#",loginStatus);
// this is to perfrom insert opertion on the userinformation table
NSString *json_string = [[NSString alloc] initWithData:webData encoding:NSUTF8StringEncoding];
NSDictionary *result = [json_string JSONValue];
//
BOOL errortest = [[result objectForKey:#"isError"] boolValue];
if(errortest == FALSE)
{
values = [result objectForKey:#"Result"];
NSLog(#"Valid User");
}
else
{
NSLog(#"Invalid User");
}
NSMutableArray *results = [[NSMutableArray alloc] init];
for (int index = 0; index<[values count]; index++) {
NSMutableDictionary * value = [values objectAtIndex:index];
Result * result = [[Result alloc] init];
result.UserID = [value objectForKey:#"UserId"];
result.FirstName = [value objectForKey:#"FirstName"];
result.LastName =[value objectForKey:#"LastName"];
result.Email =[value objectForKey:#"Email"];
result.ProfileImage =[value objectForKey:#"ProfileImage"];
result.ThumbnailImage =[value objectForKey:#"ThumbnailImage"];
result.DeviceInfoId =[value objectForKey:#"DeviceInfoId"];
NSLog(#"%#",result.UserID);
[results addObject:result];
[result release];
}
for (int index = 0; index<[results count]; index++) {
Result * result = [results objectAtIndex:index];
//save the object variables to database here
[self createEditableCopyOfDatabaseIfNeeded];
NSString *filePath = [self getWritableDBPath];
sqlite3 *database;
//this four lines of code are for creating timestap and journeyID in userjourney table.
//NSTimeInterval timeStamp = [[NSDate date] timeIntervalSince1970];
// NSNumber *timeStampObj = [NSNumber numberWithInt: timeStamp];
// NSLog(#"%#",timeStampObj);
// NSString *journeyid = [NSString stringWithFormat:#"%#_%#_%#", result.UserID, result.DeviceInfoId, timeStampObj];
if(sqlite3_open([filePath UTF8String], &database) == SQLITE_OK) {
const char *sqlStatement = "insert into UserInformation(UserID,DeviceId,Username,Password,FirstName,Email) VALUES (?,?,?,?,?,?)";
sqlite3_stmt *compiledStatement;
if(sqlite3_prepare_v2(database, sqlStatement, -1, &compiledStatement, NULL) == SQLITE_OK) {
//sqlite3_bind_text( compiledStatement, 1, [journeyid UTF8String],-1,SQLITE_TRANSIENT);
sqlite3_bind_text( compiledStatement, 1, [result.UserID UTF8String],-1,SQLITE_TRANSIENT);
sqlite3_bind_text(compiledStatement, 2, [result.DeviceInfoId UTF8String],-1,SQLITE_TRANSIENT);
sqlite3_bind_text(compiledStatement, 3, [Uname.text UTF8String],-1,SQLITE_TRANSIENT);
sqlite3_bind_text(compiledStatement, 4, [Password.text UTF8String],-1,SQLITE_TRANSIENT);
sqlite3_bind_text (compiledStatement, 5, [result.FirstName UTF8String],-1,SQLITE_TRANSIENT);
sqlite3_bind_text (compiledStatement, 6, [result.Email UTF8String],-1,SQLITE_TRANSIENT);
}
if(sqlite3_step(compiledStatement) != SQLITE_DONE ) {
NSLog( #"Save Error: %s", sqlite3_errmsg(database) );
}
else {
UIAlertView *alert = [[UIAlertView alloc]initWithTitle:#"UIAlertView" message:#"Record added" delegate:self cancelButtonTitle:#"OK" otherButtonTitles:nil];
[alert show];
[alert release];
alert = nil;
}
sqlite3_finalize(compiledStatement);
}
sqlite3_close(database);
}
[loginStatus release];
[connection release];
[webData release];
}
-(IBAction)buttonPressed:(id)sender
{
[[Reachability sharedReachability] setHostName:kHostName];
//Set Reachability class to notifiy app when the network status changes.
[[Reachability sharedReachability] setNetworkStatusNotificationsEnabled:YES];
//Set a method to be called when a notification is sent.
[[NSNotificationCenter defaultCenter] addObserver:self selector:#selector(reachabilityChanged:) name:#"kNetworkReachabilityChangedNotification" object:nil];
[self updateStatus];
[self sendRequest];
//NSLog(<#NSString *format#>)
//this is to select username and password from database.
[self check];
//Gpassq = Password.text;
//Gunameq = Uname.text;
//[self check];
}
- (void)reachabilityChanged:(NSNotification *)note {
[self updateStatus];
}
- (void)updateStatus
{
// Query the SystemConfiguration framework for the state of the device's network connections.
self.internetConnectionStatus = [[Reachability sharedReachability] internetConnectionStatus];
if (self.internetConnectionStatus == NotReachable) {
//show an alert to let the user know that they can't connect...
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Network Status"
message:#"Sorry, our network guro determined that the network is not available. Please try again later."
delegate:self
cancelButtonTitle:nil
otherButtonTitles:#"OK", nil];
[alert show];
} else {
// If the network is reachable, make sure the login button is enabled.
//_loginButton.enabled = YES;
}
}
It's very simple. First get your userName and all the values related to the user from Sqlite database on tap of submit button. If all the values found nil then you proceed with the server process. if all the values found in database proceed directly to next screen of the application.
EDIT
Pseudo Code-
- (IBAction)SubmitTapped:(id) sender {
//Check if Database already contains userName and password
if(userName && password){
//user name and password found in database
//show next screen or authenticate user through web services as per your requirement.
}
else {
//First time login
//Validate user entered data like values of textfields.(Suggestion use DHValidation for validating textfields)
BOOL validate = [self validateData];//a function to validate data using DHValidation create yourself.
if(validate){
//save login credentails into database
//show next screen
}
}
}
I hope you understand now.
UPDATE
-(void)check
{
app.journeyList = [[NSMutableArray alloc]init];
[self createEditableCopyOfDatabaseIfNeeded];
NSString *filePath = [self getWritableDBPath];
sqlite3 *database;
if(sqlite3_open([filePath UTF8String], &database) == SQLITE_OK) {
const char *sqlStatement = "SELECT Username,Password FROM UserInformation where Username=? and Password=?";
sqlite3_stmt *compiledStatement;
if(sqlite3_prepare_v2(database, sqlStatement, -1, &compiledStatement, NULL) == SQLITE_OK) {
sqlite3_bind_text(compiledStatement, 1, [Uname.text UTF8String], -1, SQLITE_TRANSIENT);
sqlite3_bind_text(compiledStatement, 2, [Password.text UTF8String], -1, SQLITE_TRANSIENT);
//NSString *loginname= [NSString stringWithUTF8String:(char *)sqlite3_column_text(compiledStatement, 1)];
// NSString *loginPassword = [NSString stringWithUTF8String:(char *)sqlite3_column_text(compiledStatement, 2)];
}
if(sqlite3_step(compiledStatement) != SQLITE_ROW ) {
//NSLog( #"Save Error: %s", sqlite3_errmsg(database) );
// UIAlertView *alert = [[UIAlertView alloc]initWithTitle:#"UIAlertView" message:#"User is not valid" delegate:self cancelButtonTitle:#"OK" otherButtonTitles:nil];
// [alert show];
// [alert release];
// alert = nil;
//we have no data into database so send request to webserver.
yourAppDelegate *appDelegate = [[UIApplication sharedApplication] delegate];
if(appDelegate.internetConnectionStatus != NotReachable){
//Network Available
[self sendRequest];
}
}
else {
isUserValid = YES;
if (isUserValid) {
app = (JourneyAppDelegate *)[[UIApplication sharedApplication]delegate];
TTabBar *tabbar=[[TTabBar alloc] init];
[app.navigationController pushViewController:tabbar animated:YES];
tabbar.selectedIndex = 0;
}
}
sqlite3_finalize(compiledStatement);
}
sqlite3_close(database);
}
//this is used when the user first time log in the server and sends
-(void)sendRequest {
UIDevice *device = [UIDevice currentDevice];
NSString *udid = [device uniqueIdentifier];
NSString *sysname = [device systemName];
NSString *sysver = [device systemVersion];
NSString *model = [device model];
NSLog(#"idis:%#",[device uniqueIdentifier]);
NSLog(#"system nameis :%#",[device systemName]);
NSLog(#"System version is:%#",[device systemVersion]);
NSLog(#"System model is:%#",[device model]);
NSLog(#"device orientation is:%d",[device orientation]);
NSString *post = [NSString stringWithFormat:#"Loginkey=%#&Password=%#&DeviceCode=%#&Firmware=%#&IMEI=%#",Uname.text,Password.text,model,sysver,udid];
NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSString *postLength = [NSString stringWithFormat:#"%d", [postData length]];
NSLog(#"%#",postLength);
NSMutableURLRequest *request = [[[NSMutableURLRequest alloc] init] autorelease];
[request setURL:[NSURL URLWithString:#"http://192.168.0.1:96/JourneyMapperAPI?RequestType=Login"]];
[request setHTTPMethod:#"POST"];
[request setValue:postLength forHTTPHeaderField:#"Content-Length"];
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
[request setHTTPBody:postData];
NSURLConnection *theConnection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
if (theConnection) {
webData = [[NSMutableData data] retain];
NSLog(#"%#",webData);
}
else
{
}
}
-(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
[webData setLength: 0];
}
-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
[webData appendData:data];
}
-(void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
[connection release];
[webData release];
}
-(void)connectionDidFinishLoading:(NSURLConnection *)connection
{
NSString *loginStatus = [[NSString alloc] initWithBytes: [webData mutableBytes] length:[webData length] encoding:NSUTF8StringEncoding];
NSLog(#"%#",loginStatus);
// this is to perfrom insert opertion on the userinformation table
NSString *json_string = [[NSString alloc] initWithData:webData encoding:NSUTF8StringEncoding];
NSDictionary *result = [json_string JSONValue];
//
BOOL errortest = [[result objectForKey:#"isError"] boolValue];
if(errortest == FALSE)
{
values = [result objectForKey:#"Result"];
NSLog(#"Valid User");
}
else
{
NSLog(#"Invalid User");
}
NSMutableArray *results = [[NSMutableArray alloc] init];
for (int index = 0; index<[values count]; index++) {
NSMutableDictionary * value = [values objectAtIndex:index];
Result * result = [[Result alloc] init];
result.UserID = [value objectForKey:#"UserId"];
result.FirstName = [value objectForKey:#"FirstName"];
result.LastName =[value objectForKey:#"LastName"];
result.Email =[value objectForKey:#"Email"];
result.ProfileImage =[value objectForKey:#"ProfileImage"];
result.ThumbnailImage =[value objectForKey:#"ThumbnailImage"];
result.DeviceInfoId =[value objectForKey:#"DeviceInfoId"];
NSLog(#"%#",result.UserID);
[results addObject:result];
[result release];
}
for (int index = 0; index<[results count]; index++) {
Result * result = [results objectAtIndex:index];
//save the object variables to database here
[self createEditableCopyOfDatabaseIfNeeded];
NSString *filePath = [self getWritableDBPath];
sqlite3 *database;
//this four lines of code are for creating timestap and journeyID in userjourney table.
//NSTimeInterval timeStamp = [[NSDate date] timeIntervalSince1970];
// NSNumber *timeStampObj = [NSNumber numberWithInt: timeStamp];
// NSLog(#"%#",timeStampObj);
// NSString *journeyid = [NSString stringWithFormat:#"%#_%#_%#", result.UserID, result.DeviceInfoId, timeStampObj];
if(sqlite3_open([filePath UTF8String], &database) == SQLITE_OK) {
const char *sqlStatement = "insert into UserInformation(UserID,DeviceId,Username,Password,FirstName,Email) VALUES (?,?,?,?,?,?)";
sqlite3_stmt *compiledStatement;
if(sqlite3_prepare_v2(database, sqlStatement, -1, &compiledStatement, NULL) == SQLITE_OK) {
//sqlite3_bind_text( compiledStatement, 1, [journeyid UTF8String],-1,SQLITE_TRANSIENT);
sqlite3_bind_text( compiledStatement, 1, [result.UserID UTF8String],-1,SQLITE_TRANSIENT);
sqlite3_bind_text(compiledStatement, 2, [result.DeviceInfoId UTF8String],-1,SQLITE_TRANSIENT);
sqlite3_bind_text(compiledStatement, 3, [Uname.text UTF8String],-1,SQLITE_TRANSIENT);
sqlite3_bind_text(compiledStatement, 4, [Password.text UTF8String],-1,SQLITE_TRANSIENT);
sqlite3_bind_text (compiledStatement, 5, [result.FirstName UTF8String],-1,SQLITE_TRANSIENT);
sqlite3_bind_text (compiledStatement, 6, [result.Email UTF8String],-1,SQLITE_TRANSIENT);
}
if(sqlite3_step(compiledStatement) != SQLITE_DONE ) {
NSLog( #"Save Error: %s", sqlite3_errmsg(database) );
}
else {
UIAlertView *alert = [[UIAlertView alloc]initWithTitle:#"UIAlertView" message:#"Record added" delegate:self cancelButtonTitle:#"OK" otherButtonTitles:nil];
[alert show];
[alert release];
alert = nil;
}
sqlite3_finalize(compiledStatement);
}
sqlite3_close(database);
}
[loginStatus release];
[connection release];
[webData release];
}
-(IBAction)buttonPressed:(id)sender
{
//it should be on application did finish launching
[[Reachability sharedReachability] setHostName:kHostName];
//Set Reachability class to notifiy app when the network status changes.
[[Reachability sharedReachability] setNetworkStatusNotificationsEnabled:YES];
//Set a method to be called when a notification is sent.
[[NSNotificationCenter defaultCenter] addObserver:self selector:#selector(reachabilityChanged:) name:#"kNetworkReachabilityChangedNotification" object:nil];
//it will be called automatically you don't need to expilictly call this function
// [self updateStatus];
//The above code should be in application did finish launching.
//NSLog(<#NSString *format#>)
//this is to select username and password from database.
[self check];
//Gpassq = Password.text;
//Gunameq = Uname.text;
//[self check];
}
- (void)reachabilityChanged:(NSNotification *)note {
[self updateStatus];
}
- (void)updateStatus
{
// Query the SystemConfiguration framework for the state of the device's network connections.
self.internetConnectionStatus = [[Reachability sharedReachability] internetConnectionStatus];
if (self.internetConnectionStatus == NotReachable) {
//show an alert to let the user know that they can't connect...
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Network Status"
message:#"Sorry, our network guro determined that the network is not available. Please try again later."
delegate:self
cancelButtonTitle:nil
otherButtonTitles:#"OK", nil];
[alert show];
} else {
// If the network is reachable, make sure the login button is enabled.
//_loginButton.enabled = YES;
}
}
Related
Am using SQLite3. and am updating row which is already present by using following code
- (BOOL)updateTableData :(NSString *) num
{
AppDelegate *appDelegate = (AppDelegate *)[UIApplication sharedApplication].delegate;
dbPath = [self getDBPath:#"studentslist.sqlite"];
if(sqlite3_open([dbPath UTF8String], &database) == SQLITE_OK)
{
sqlite3_stmt *updateStmt;
const char *sql = "update studentInfo set sAge=?, sAddrs1=?, sAddrs2=?, sMobile =?, sClass =? where sRollNumber=?;";
if(sqlite3_prepare_v2(database, sql, -1, &updateStmt, NULL) != SQLITE_OK)
{
NSLog(#"updateTableData: Error while creating delete statement. '%s'", sqlite3_errmsg(database));
return;
}
NSLog(#"appDelegate.updateArray %#",appDelegate.updateArray);
sqlite3_bind_int(updateStmt, 1,[[appDelegate.updateArray objectAtIndex:0] intValue]);
sqlite3_bind_text(updateStmt, 2,[[appDelegate.updateArray objectAtIndex:1] UTF8String], -1,SQLITE_TRANSIENT);
sqlite3_bind_text(updateStmt, 3,[[appDelegate.updateArray objectAtIndex:2] UTF8String], -1,SQLITE_TRANSIENT);
sqlite3_bind_text(updateStmt, 4,[[appDelegate.updateArray objectAtIndex:3] UTF8String], -1,SQLITE_TRANSIENT);
sqlite3_bind_text(updateStmt, 5,[[appDelegate.updateArray objectAtIndex:4] UTF8String], -1,SQLITE_TRANSIENT);
if (SQLITE_DONE != sqlite3_step(updateStmt))
{
NSLog(#"updateTableData: Error while updating. '%s'", sqlite3_errmsg(database));
sqlite3_finalize(updateStmt);
sqlite3_reset(updateStmt);
sqlite3_close(database);
return NO;
}
else
{
NSLog(#"updateTableData: Updated");
sqlite3_finalize(updateStmt);
sqlite3_close(database);
return YES;
}
}
else
{
NSLog(#"updateTableData :Database Not Opened");
sqlite3_close(database);
return NO;
}
in main class am calling this method as follows
-(IBAction)updateButtonAction:(id)sender
{
AppDelegate *appDelegate = (AppDelegate *)[UIApplication sharedApplication].delegate;
db = [[Database alloc]init];
if ([ageTxtFld.text length]>0 && [address1TxtFld.text length]>0 && [address2TxtFld.text length]>0 && [mobileTxtFld.text length]>0 && [classTxtFld.text length]>0)
{
[appDelegate.updateArray addObject:ageTxtFld.text];
[appDelegate.updateArray addObject:address1TxtFld.text];
[appDelegate.updateArray addObject:address2TxtFld.text];
[appDelegate.updateArray addObject:mobileTxtFld.text];
[appDelegate.updateArray addObject:classTxtFld.text];
NSLog(#"appDelegate.updateArray %#",appDelegate.updateArray);
NSString *num = rollNumberTxtFld.text;
BOOL is = [db updateTableData:num];
if (is == YES)
{
updateAlert = [[UIAlertView alloc] initWithTitle:#"Success" message:#"Updated" delegate:self cancelButtonTitle:#"Ok" otherButtonTitles:nil, nil];
[updateAlert show];
}
else
{
updateAlert = [[UIAlertView alloc] initWithTitle:#"Fail" message:#"Not Updated" delegate:self cancelButtonTitle:#"Ok" otherButtonTitles:nil, nil];
[updateAlert show];
}
}
else
{
UIAlertView *errorAlert = [[UIAlertView alloc] initWithTitle:#"Error" message:#"Enter all values" delegate:self cancelButtonTitle:#"Ok" otherButtonTitles:nil, nil];
[errorAlert show];
}
}
But it always printing NSLog(#"updateTableData: Updated"); but not updating
Any one can suggest me or help with code.
Thanks in Advance
- (void)createEditableCopyOfDatabaseIfNeeded {
BOOL success;
NSFileManager *fileManager = [NSFileManager defaultManager];
NSError *error;
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *writableDBPath = [documentsDirectory stringByAppendingPathComponent:#"studentslist.sqlite"];
dbPath =writableDBPath;
[databasePath retain];
success = [fileManager fileExistsAtPath:writableDBPath];
if (success) return;
NSString *defaultDBPath = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:#"studentslist.sqlite"];
success = [fileManager copyItemAtPath:defaultDBPath toPath:writableDBPath error:&error];
if (!success) {
NSAssert1(0, #"Failed to create writable database file with message '%#'.", [error localizedDescription]);
}
writableDBPath = nil;
documentsDirectory = nil;
paths = nil;
}
Write this method in your code and call it. surely this was a problem in your code.
I have my sqlite database. now i want syncing with icloud. I read blogs saying sqlite syncing with icloud is not supported. Either go for core data OR "Do what exactly core data does".
Now it is not posible for me to go for core data.So like second option "Do something similar to how CoreData syncs sqlite DBs: send "transaction logs" to iCloud instead and build each local sqlite file off of those."
please can anyone share any sample code for "transaction log" of sqlite OR can expalin in detail stepwise what i need to do?
1) I followed this link to create xml. You can download respective api from its github.Link is - http://arashpayan.com/blog/2009/01/14/apxml-nsxmldocument-substitute-for-iphoneipod-touch/
2) on button click:
-(IBAction) btniCloudPressed:(id)sender
{
// create the document with it’s root element
APDocument *doc = [[APDocument alloc] initWithRootElement:[APElement elementWithName:#"Properties"]];
APElement *rootElement = [doc rootElement]; // retrieves same element we created the line above
NSMutableArray *addrList = [[NSMutableArray alloc] init];
NSString *select_query;
const char *select_stmt;
sqlite3_stmt *compiled_stmt;
if (sqlite3_open([[app getDBPath] UTF8String], &dbconn) == SQLITE_OK)
{
select_query = [NSString stringWithFormat:#"SELECT * FROM Properties"];
select_stmt = [select_query UTF8String];
if(sqlite3_prepare_v2(dbconn, select_stmt, -1, &compiled_stmt, NULL) == SQLITE_OK)
{
while(sqlite3_step(compiled_stmt) == SQLITE_ROW)
{
NSString *addr = [NSString stringWithFormat:#"%#",[NSString stringWithUTF8String:(char *)sqlite3_column_text(compiled_stmt,0)]];
addr = [NSString stringWithFormat:#"%##%#",addr,[NSString stringWithUTF8String:(char *)sqlite3_column_text(compiled_stmt,1)]];
addr = [NSString stringWithFormat:#"%##%#",addr,[NSString stringWithUTF8String:(char *)sqlite3_column_text(compiled_stmt,2)]];
addr = [NSString stringWithFormat:#"%##%#",addr,[NSString stringWithUTF8String:(char *)sqlite3_column_text(compiled_stmt,3)]];
addr = [NSString stringWithFormat:#"%##%#",addr,[NSString stringWithUTF8String:(char *)sqlite3_column_text(compiled_stmt,4)]];
addr = [NSString stringWithFormat:#"%##%#",addr,[NSString stringWithUTF8String:(char *)sqlite3_column_text(compiled_stmt,5)]];
addr = [NSString stringWithFormat:#"%##%#",addr,[NSString stringWithUTF8String:(char *)sqlite3_column_text(compiled_stmt,6)]];
addr = [NSString stringWithFormat:#"%##%#",addr,[NSString stringWithUTF8String:(char *)sqlite3_column_text(compiled_stmt,7)]];
//NSLog(#"%#",addr);
[addrList addObject:addr];
}
sqlite3_finalize(compiled_stmt);
}
else
{
NSLog(#"Error while creating detail view statement. '%s'", sqlite3_errmsg(dbconn));
}
}
for(int i =0 ; i < [addrList count]; i++)
{
NSArray *addr = [[NSArray alloc] initWithArray:[[addrList objectAtIndex:i] componentsSeparatedByString:#"#"]];
APElement *property = [APElement elementWithName:#"Property"];
[property addAttributeNamed:#"id" withValue:[addr objectAtIndex:0]];
[property addAttributeNamed:#"street" withValue:[addr objectAtIndex:1]];
[property addAttributeNamed:#"city" withValue:[addr objectAtIndex:2]];
[property addAttributeNamed:#"state" withValue:[addr objectAtIndex:3]];
[property addAttributeNamed:#"zip" withValue:[addr objectAtIndex:4]];
[property addAttributeNamed:#"status" withValue:[addr objectAtIndex:5]];
[property addAttributeNamed:#"lastupdated" withValue:[addr objectAtIndex:6]];
[property addAttributeNamed:#"deleted" withValue:[addr objectAtIndex:7]];
[rootElement addChild:property];
[property release];
APElement *fullscore = [APElement elementWithName:#"FullScoreReport"];
[property addChild:fullscore];
[fullscore release];
select_query = [NSString stringWithFormat:#"SELECT AnsNo,Answer,AnswerScore,MaxScore,AnsIndex FROM FullScoreReport WHERE Addr_ID = %#",[addr objectAtIndex:0]];
select_stmt = [select_query UTF8String];
if(sqlite3_prepare_v2(dbconn, select_stmt, -1, &compiled_stmt, NULL) == SQLITE_OK)
{
while(sqlite3_step(compiled_stmt) == SQLITE_ROW)
{
APElement *answer = [APElement elementWithName:#"Answer"];
[answer addAttributeNamed:#"AnsNo" withValue:[NSString stringWithFormat:#"%#",[NSString stringWithUTF8String:(char *)sqlite3_column_text(compiled_stmt,0)]]];
[answer addAttributeNamed:#"Answer" withValue:[NSString stringWithFormat:#"%#",[NSString stringWithUTF8String:(char *)sqlite3_column_text(compiled_stmt,1)]]];
[answer addAttributeNamed:#"AnswerScore" withValue:[NSString stringWithFormat:#"%#",[NSString stringWithUTF8String:(char *)sqlite3_column_text(compiled_stmt,2)]]];
[answer addAttributeNamed:#"MaxScore" withValue:[NSString stringWithFormat:#"%#",[NSString stringWithUTF8String:(char *)sqlite3_column_text(compiled_stmt,3)]]];
[answer addAttributeNamed:#"AnsIndex" withValue:[NSString stringWithFormat:#"%#",[NSString stringWithUTF8String:(char *)sqlite3_column_text(compiled_stmt,4)]]];
[fullscore addChild:answer];
[answer release];
}
sqlite3_finalize(compiled_stmt);
}
}
sqlite3_close(dbconn);
NSString *prettyXML = [doc prettyXML];
NSLog(#"\n\n%#",prettyXML);
//***** PARSE XML FILE *****
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *path = [[paths objectAtIndex:0] stringByAppendingPathComponent:#"Properties.xml" ];
NSData *file = [NSData dataWithBytes:[prettyXML UTF8String] length:strlen([prettyXML UTF8String])];
[file writeToFile:path atomically:YES];
NSString *fileName = [NSString stringWithFormat:#"Properties.xml"];
NSURL *ubiq = [[NSFileManager defaultManager]URLForUbiquityContainerIdentifier:nil];
NSURL *ubiquitousPackage = [[ubiq URLByAppendingPathComponent:#"Documents"] URLByAppendingPathComponent:fileName];
MyDocument *mydoc = [[MyDocument alloc] initWithFileURL:ubiquitousPackage];
mydoc.xmlContent = prettyXML;
[mydoc saveToURL:[mydoc fileURL]forSaveOperation:UIDocumentSaveForCreating completionHandler:^(BOOL success)
{
if (success)
{
NSLog(#"XML: Synced with icloud");
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"iCloud Syncing" message:#"Successfully synced with iCloud." delegate:self cancelButtonTitle:#"OK" otherButtonTitles:nil];
[alert show];
[alert release];
}
else
NSLog(#"XML: Syncing FAILED with icloud");
}];
}
3)MyDocument.h file
#import <UIKit/UIKit.h>
#interface MyDocument : UIDocument
#property (strong) NSString *xmlContent;
#end
4)MyDocument.m file
#import "MyDocument.h"
#implementation MyDocument
#synthesize xmlContent,zipDataContent;
// Called whenever the application reads data from the file system
- (BOOL)loadFromContents:(id)contents ofType:(NSString *)typeName error:(NSError **)outError
{
// NSLog(#"* ---> typename: %#",typeName);
self.xmlContent = [[NSString alloc]
initWithBytes:[contents bytes]
length:[contents length]
encoding:NSUTF8StringEncoding];
[[NSNotificationCenter defaultCenter] postNotificationName:#"noteModified" object:self];
return YES;
}
// Called whenever the application (auto)saves the content of a note
- (id)contentsForType:(NSString *)typeName error:(NSError **)outError
{
return [NSData dataWithBytes:[self.xmlContent UTF8String] length:[self.xmlContent length]];
}
#end
5) now in ur appdelegate
- (void)loadData:(NSMetadataQuery *)queryData
{
for (NSMetadataItem *item in [queryData results])
{
NSString *filename = [item valueForAttribute:NSMetadataItemDisplayNameKey];
NSNumber *filesize = [item valueForAttribute:NSMetadataItemFSSizeKey];
NSDate *updated = [item valueForAttribute:NSMetadataItemFSContentChangeDateKey];
NSLog(#"%# (%# bytes, updated %#) ", filename, filesize, updated);
NSURL *url = [item valueForAttribute:NSMetadataItemURLKey];
MyDocument *doc = [[MyDocument alloc] initWithFileURL:url];
if([filename isEqualToString:#"Properties"])
{
[doc openWithCompletionHandler:^(BOOL success) {
if (success) {
NSLog(#"XML: Success to open from iCloud");
NSData *file = [NSData dataWithContentsOfURL:url];
//NSString *xmlFile = [[NSString alloc] initWithData:file encoding:NSASCIIStringEncoding];
//NSLog(#"%#",xmlFile);
NSXMLParser *parser = [[NSXMLParser alloc] initWithData:file];
[parser setDelegate:self];
[parser parse];
//We hold here until the parser finishes execution
[parser release];
}
else
{
NSLog(#"XML: failed to open from iCloud");
}
}];
}
}
}
6) now in parser method fetch data and insert/update as needed in database.
- (void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)nameSpaceURI qualifiedName:(NSString *)qName attributes:(NSDictionary *)attributeDict
{
if ([elementName isEqual:#"Property"])
{
NSLog(#"Property attributes : %#|%#|%#|%#|%#|%#|%#|%#", [attributeDict objectForKey:#"id"],[attributeDict objectForKey:#"street"], [attributeDict objectForKey:#"city"], [attributeDict objectForKey:#"state"],[attributeDict objectForKey:#"zip"],[attributeDict objectForKey:#"status"],[attributeDict objectForKey:#"lastupdated"],[attributeDict objectForKey:#"deleted"]);
}
//like this way fetch all data and insert in db
}
MGTwitterEngine.m
- (NSString *)username
{
return [[_username retain] autorelease];
}
- (NSString *)password
{
return [[_password retain] autorelease];
}
- (void)setUsername:(NSString *)newUsername password:(NSString *)newPassword
{
// Set new credentials.
[_username release];
_username = [newUsername retain];
[_password release];
_password = [newPassword retain];
if ([self clearsCookies]) {
// Remove all cookies for twitter, to ensure next connection uses new credentials.
NSString *urlString = [NSString stringWithFormat:#"%#://%#",
(_secureConnection) ? #"https" : #"http",
_APIDomain];
NSURL *url = [NSURL URLWithString:urlString];
NSHTTPCookieStorage *cookieStorage = [NSHTTPCookieStorage sharedHTTPCookieStorage];
NSEnumerator *enumerator = [[cookieStorage cookiesForURL:url] objectEnumerator];
NSHTTPCookie *cookie = nil;
while (cookie == [enumerator nextObject]) {
[cookieStorage deleteCookie:cookie];
}
}
}
- (NSString *)sendUpdate:(NSString *)status
{
return [self sendUpdate:status inReplyTo:0];
}
- (NSString *)sendUpdate:(NSString *)status inReplyTo:(unsigned long)updateID
{
if (!status) {
return nil;
}
NSString *path = [NSString stringWithFormat:#"statuses/update.%#", API_FORMAT];
NSString *trimmedText = status;
if ([trimmedText length] > MAX_MESSAGE_LENGTH) {
trimmedText = [trimmedText substringToIndex:MAX_MESSAGE_LENGTH];
}
NSMutableDictionary *params = [NSMutableDictionary dictionaryWithCapacity:0];
[params setObject:trimmedText forKey:#"status"];
if (updateID > 0) {
[params setObject:[NSString stringWithFormat:#"%u", updateID] forKey:#"in_reply_to_status_id"];
}
NSString *body = [self _queryStringWithBase:nil parameters:params prefixed:NO];
return [self _sendRequestWithMethod:HTTP_POST_METHOD path:path
queryParameters:params body:body
requestType:MGTwitterUpdateSendRequest
responseType:MGTwitterStatus];
}
TwitterPostViewController.m
- (IBAction)submitTweet{
[tweet resignFirstResponder];
if([[tweet text] length] > 0){
NSLog(#"%#",[[NSUserDefaults standardUserDefaults] valueForKey:#"TwitterUsername"]);
NSLog(#"%#",[[NSUserDefaults standardUserDefaults] valueForKey:#"TwitterPassword"]);
[[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:YES];
[engine sendUpdate:[tweet text]];
}
}
- (void)requestFailed:(NSString *)requestIdentifier withError:(NSError *)error{
NSLog(#"Fail: %#", error);
[[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:NO];
UIAlertView *failAlert;
if([error code] == 401){
failAlert = [[UIAlertView alloc] initWithTitle:#"Error" message:#"Incorrect Username & Password." delegate:nil cancelButtonTitle:#"OK" otherButtonTitles:nil];
[failAlert setTag:10];
[failAlert setDelegate:self];
}
else
{
failAlert = [[UIAlertView alloc] initWithTitle:#"Error" message:#"Failed sending status to Twitter." delegate:nil cancelButtonTitle:#"OK" otherButtonTitles:nil];
}
[failAlert show];
[failAlert release];
}
It shows me the fail popup of Incorrect username and password
I have checked through nslog that username and password are going correct.
what could be wrong?
It looks like the version of MGTwitterEngine you're using is trying to use basic auth. That was switched off in Twitter in favour of OAuth. Get a newer version of MGTwitterEngine (or a fork that supports OAuth).
I have an application in which I am posting data to my server API database through HTTP POST method and get response in JSON format. I want to read the JSON data and save it in SQLite database. I have done with posting data to Web server API through HTTP POST method but reading the JSON data and saving it in database has not been achieved.
I have created a class which consists of all the JSON array objects.
This is .h file:
#import <Foundation/Foundation.h>
//TokenID":"Vao13gifem","isError":false,"ErrorMessage":"","Result":[{"UserId":"153","FirstName":"Rocky","LastName":"Yadav","Email":"rocky#itg.com","ProfileImage":null,"ThumbnailImage":null,"DeviceInfoId":"12"}],"ErrorCode":900}
//Terminating in response to SpringBoard's termination.
#interface Result : NSObject {
NSString * UserID;
NSString *FirstName;
NSString *LastName;
NSString *Email;
NSString *ProfileImage;
NSString *ThumbnailImage;
NSString *DeviceInfoId;
}
#property (nonatomic,retain) NSString *UserID;
#property (nonatomic,retain) NSString *FirstName;
#property (nonatomic,retain) NSString *LastName;
#property (nonatomic,retain) NSString *Email;
#property (nonatomic,retain) NSString *ProfileImage;
#property (nonatomic,retain) NSString *ThumbnailImage;
#property (nonatomic,retain) NSString *DeviceInfoId;
#end
This is .m file
#import "Result.h"
#implementation Result
#synthesize UserID;
#synthesize FirstName;
#synthesize LastName;
#synthesize Email;
#synthesize ProfileImage;
#synthesize ThumbnailImage;
#synthesize DeviceInfoId;
- (void)dealloc {
[super dealloc];
[UserID release];
[FirstName release];
[LastName release];
[Email release];
[ProfileImage release];
[ThumbnailImage release];
[DeviceInfoId release];
}
#end
This is my apicontroller.m
#import "apicontroller.h"
#import "Result.h"
#import <sqlite3.h>
#define DATABASE_NAME #"journey.sqlite"
#define DATABASE_TITLE #"journey"
#implementation apicontroller
#synthesize txtUserName;
#synthesize txtPassword;
#synthesize txtfirstName;
#synthesize txtlast;
#synthesize txtEmail;
#synthesize webData;
- (NSString *) getWritableDBPath {
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory , NSUserDomainMask, YES);
NSString *documentsDir = [paths objectAtIndex:0];
return [documentsDir stringByAppendingPathComponent:DATABASE_NAME];
}
-(void)createEditableCopyOfDatabaseIfNeeded
{
// Testing for existence
BOOL success;
NSFileManager *fileManager = [NSFileManager defaultManager];
NSError *error;
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,
NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *writableDBPath = [documentsDirectory stringByAppendingPathComponent:DATABASE_NAME];
NSLog(#"%#",writableDBPath);
success = [fileManager fileExistsAtPath:writableDBPath];
if (success)
return;
// The writable database does not exist, so copy the default to
// the appropriate location.
NSString *defaultDBPath = [[[NSBundle mainBundle] resourcePath]
stringByAppendingPathComponent:DATABASE_NAME];
success = [fileManager copyItemAtPath:defaultDBPath
toPath:writableDBPath
error:&error];
if(!success)
{
NSAssert1(0,#"Failed to create writable database file with Message : '%#'.",
[error localizedDescription]);
}
}
-(void)sendRequest
{
UIDevice *device = [UIDevice currentDevice];
NSString *udid = [device uniqueIdentifier];
NSString *sysname = [device systemName];
NSString *sysver = [device systemVersion];
NSString *model = [device model];
NSLog(#"idis:%#",[device uniqueIdentifier]);
NSLog(#"system nameis :%#",[device systemName]);
NSLog(#"System version is:%#",[device systemVersion]);
NSLog(#"System model is:%#",[device model]);
NSLog(#"device orientation is:%d",[device orientation]);
NSString *post = [NSString stringWithFormat:#"Loginkey=%#&Password=%#&DeviceCode=%#&Firmware=%#&IMEI=%#",txtUserName.text,txtPassword.text,model,sysver,udid];
NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSString *postLength = [NSString stringWithFormat:#"%d", [postData length]];
NSLog(#"%#",postLength);
NSMutableURLRequest *request = [[[NSMutableURLRequest alloc] init] autorelease];
[request setURL:[NSURL URLWithString:#"http://192.168.0.68:91/JourneyMapperAPI?RequestType=Login"]];
[request setHTTPMethod:#"POST"];
[request setValue:postLength forHTTPHeaderField:#"Content-Length"];
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
[request setHTTPBody:postData];
NSURLConnection *theConnection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
if (theConnection) {
webData = [[NSMutableData data] retain];
NSLog(#"%#",webData);
}
else
{
}
}
-(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
[webData setLength: 0];
}
-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
[webData appendData:data];
}
-(void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
[connection release];
[webData release];
}
-(void)connectionDidFinishLoading:(NSURLConnection *)connection
{
NSString *loginStatus = [[NSString alloc] initWithBytes: [webData mutableBytes] length:[webData length] encoding:NSUTF8StringEncoding];
NSLog(#"%#",loginStatus);
NSString *json_string = [[NSString alloc] initWithData:webData encoding:NSUTF8StringEncoding];
NSDictionary *result = [json_string JSONValue];
NSArray *values = [result objectForKey:#"Result"];
NSMutableArray *results = [[NSMutableArray alloc] init];
for (int index = 0; index<[values count]; index++) {
NSMutableDictionary * value = [values objectAtIndex:index];
Result * result = [[Result alloc] init];
result.UserID = [value objectForKey:#"UserId"];
result.FirstName = [value objectForKey:#"FirstName"];
result.LastName =[value objectForKey:#"LastName"];
result.Email =[value objectForKey:#"Email"];
result.ProfileImage =[value objectForKey:#"ProfileImage"];
result.ThumbnailImage =[value objectForKey:#"ThumbnailImage"];
result.DeviceInfoId =[value objectForKey:#"DeviceInfoId"];
[results addObject:result];
[result release];
}
for (int index = 0; index<[results count]; index++) {
Result * result = [results objectAtIndex:index];
//save the object variables to database here
[self createEditableCopyOfDatabaseIfNeeded];
NSString *filePath = [self getWritableDBPath];
sqlite3 *database;
if(sqlite3_open([filePath UTF8String], &database) == SQLITE_OK) {
const char *sqlStatement = "insert into UserInformation(UserID,DeviceId,FirstName,Email,) VALUES (?,?,?,?)";
sqlite3_stmt *compiledStatement;
if(sqlite3_prepare_v2(database, sqlStatement, -1, &compiledStatement, NULL) == SQLITE_OK) {
sqlite3_bind_text( compiledStatement, 1, [result.UserID UTF8String],-1,SQLITE_TRANSIENT);
sqlite3_bind_text(compiledStatement, 2, [result.DeviceInfoId UTF8String],-1,SQLITE_TRANSIENT);
sqlite3_bind_text (compiledStatement, 3, [result.FirstName UTF8String],-1,SQLITE_TRANSIENT);
sqlite3_bind_text (compiledStatement, 4, [result.Email UTF8String],-1,SQLITE_TRANSIENT);
}
if(sqlite3_step(compiledStatement) != SQLITE_DONE ) {
NSLog( #"Save Error: %s", sqlite3_errmsg(database) );
}
else {
UIAlertView *alert = [[UIAlertView alloc]initWithTitle:#"UIAlertView" message:#"Record added" delegate:self cancelButtonTitle:#"OK" otherButtonTitles:nil];
[alert show];
[alert release];
alert = nil;
}
sqlite3_finalize(compiledStatement);
}
sqlite3_close(database);
}
[loginStatus release];
[connection release];
[webData release];
}
-(IBAction)click:(id)sender
{
[self sendRequest];
}
-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{
[txtfirstName resignFirstResponder];
[txtlast resignFirstResponder];
[txtUserName resignFirstResponder];
[txtPassword resignFirstResponder];
[txtEmail resignFirstResponder];
}
// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad {
[super viewDidLoad];
//[self sendRequest];
}
/*
// Override to allow orientations other than the default portrait orientation.
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
// Return YES for supported orientations.
return (interfaceOrientation == UIInterfaceOrientationPortrait);
}
*/
- (void)didReceiveMemoryWarning {
// Releases the view if it doesn't have a superview.
[super didReceiveMemoryWarning];
// Release any cached data, images, etc. that aren't in use.
}
- (void)viewDidUnload {
[super viewDidUnload];
// Release any retained subviews of the main view.
// e.g. self.myOutlet = nil;
}
- (void)dealloc {
[super dealloc];
}
#end
In the connectionFinishLoading method it does not compare each object, it directly prints the error in NSLog:
(Save Error:near")":syntax error);
How can I fix this error?
My guess is that the trailing comma in the list of columns in your SQL statement is causing the error:
const char *sqlStatement = "insert into UserInformation(UserID,DeviceId,FirstName,Email,) VALUES (?,?,?,?)";
Note that there’s a comma between Email and ).
Try:
const char *sqlStatement = "insert into UserInformation(UserID,DeviceId,FirstName,Email) VALUES (?,?,?,?)";
instead.
hi friend i am passing tokenid throw this class to this here is my code how i am passing it wrong for
-(void)check
{
//app.journeyList = [[NSMutableArray alloc]init];
[self createEditableCopyOfDatabaseIfNeeded];
NSString *filePath = [self getWritableDBPath];
sqlite3 *database;
if(sqlite3_open([filePath UTF8String], &database) == SQLITE_OK) {
const char *sqlStatement = "SELECT Username,Password FROM UserInformation where Username=? and Password=?";
sqlite3_stmt *compiledStatement;
if(sqlite3_prepare_v2(database, sqlStatement, -1, &compiledStatement, NULL) == SQLITE_OK) {
sqlite3_bind_text(compiledStatement, 1, [txtUserName.text UTF8String], -1, SQLITE_TRANSIENT);
sqlite3_bind_text(compiledStatement, 2, [txtPassword.text UTF8String], -1, SQLITE_TRANSIENT);
//NSString *loginname= [NSString stringWithUTF8String:(char *)sqlite3_column_text(compiledStatement, 1)];
// NSString *loginPassword = [NSString stringWithUTF8String:(char *)sqlite3_column_text(compiledStatement, 2)];
}
if(sqlite3_step(compiledStatement) != SQLITE_ROW ) {
NSLog( #"Save Error: %s", sqlite3_errmsg(database) );
UIAlertView *alert = [[UIAlertView alloc]initWithTitle:#"UIAlertView" message:#"User is not valid" delegate:self cancelButtonTitle:#"OK" otherButtonTitles:nil];
[alert show];
[alert release];
alert = nil;
//We have no data in database so send request to webserver.
//apitest = [[UIApplication sharedApplication]delegate];
//if (apitest.internetConnectionStatus != NotReachable)
// {
// [self sendRequest];
// }
}
else {
isUserValid = YES;
if (isUserValid) {
UIAlertView *alert = [[UIAlertView alloc]initWithTitle:#"UIAlertView" message:#"Valid User" delegate:self cancelButtonTitle:#"OK" otherButtonTitles:nil];
[alert show];
[alert release];
}
}
sqlite3_finalize(compiledStatement);
}
sqlite3_close(database);
}
-(IBAction)update:(id)sender
{
test1 *check = [[test1 alloc]initWithNibName:#"test1" bundle:nil];
check.tokenapi1=tokenapi;;
[self presentModalViewController:check animated:YES];
//[self getStudents];
}
-(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
[webData setLength: 0];
}
-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
[webData appendData:data];
}
-(void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
[connection release];
[webData release];
}
-(void)connectionDidFinishLoading:(NSURLConnection *)connection
{
NSString *loginStatus = [[NSString alloc] initWithBytes: [webData mutableBytes] length:[webData length] encoding:NSUTF8StringEncoding];
NSLog(#"%#",loginStatus);
//this is to perfrom insert opertion on the userinformation table
NSString *json_string = [[NSString alloc] initWithData:webData encoding:NSUTF8StringEncoding];
NSDictionary *result = [json_string JSONValue];
tokenapi = [result objectForKey:#"TokenID"];
NSLog(#"this is token id:%#",tokenapi);
//
BOOL errortest = [[result objectForKey:#"isError"] boolValue];
if(errortest == FALSE)
{
values = [result objectForKey:#"Result"];
NSLog(#"Valid User");
}
else
{
NSLog(#"Invalid User");
}
NSMutableArray *results = [[NSMutableArray alloc] init];
for (int index = 0; index<[values count]; index++) {
NSMutableDictionary * value = [values objectAtIndex:index];
Result * result = [[Result alloc] init];
result.UserID = [value objectForKey:#"UserId"];
result.FirstName = [value objectForKey:#"FirstName"];
result.LastName =[value objectForKey:#"LastName"];
result.Email =[value objectForKey:#"Email"];
result.ProfileImage =[value objectForKey:#"ProfileImage"];
result.ThumbnailImage =[value objectForKey:#"ThumbnailImage"];
result.DeviceInfoId =[value objectForKey:#"DeviceInfoId"];
NSLog(#"%#",result.UserID);
ID=result.UserID;
NSLog(#"%#",ID);
[results addObject:result];
[result release];
}
for (int index = 0; index<[results count]; index++) {
Result * result = [results objectAtIndex:index];
//save the object variables to database here
[self createEditableCopyOfDatabaseIfNeeded];
NSString *filePath = [self getWritableDBPath];
sqlite3 *database;
//NSTimeInterval timeStamp = [[NSDate date] timeIntervalSince1970];
// NSNumber *timeStampObj = [NSNumber numberWithInt: timeStamp];
// NSLog(#"%#",timeStampObj);
// NSString *journeyid = [NSString stringWithFormat:#"%#_%#_%#", result.UserID, result.DeviceInfoId, timeStampObj];
if(sqlite3_open([filePath UTF8String], &database) == SQLITE_OK) {
const char *sqlStatement = "insert into UserInformation(UserID,DeviceId,Username,Password,FirstName,Email) VALUES (?,?,?,?,?,?)";
sqlite3_stmt *compiledStatement;
if(sqlite3_prepare_v2(database, sqlStatement, -1, &compiledStatement, NULL) == SQLITE_OK) {
//sqlite3_bind_text( compiledStatement, 1, [journeyid UTF8String],-1,SQLITE_TRANSIENT);
sqlite3_bind_text( compiledStatement, 1, [result.UserID UTF8String],-1,SQLITE_TRANSIENT);
sqlite3_bind_text(compiledStatement, 2, [result.DeviceInfoId UTF8String],-1,SQLITE_TRANSIENT);
sqlite3_bind_text(compiledStatement, 3, [txtUserName.text UTF8String],-1,SQLITE_TRANSIENT);
sqlite3_bind_text(compiledStatement, 4, [txtPassword.text UTF8String],-1,SQLITE_TRANSIENT);
sqlite3_bind_text (compiledStatement, 5, [result.FirstName UTF8String],-1,SQLITE_TRANSIENT);
sqlite3_bind_text (compiledStatement, 6, [result.Email UTF8String],-1,SQLITE_TRANSIENT);
}
if(sqlite3_step(compiledStatement) != SQLITE_DONE ) {
NSLog( #"Save Error: %s", sqlite3_errmsg(database) );
}
else {
UIAlertView *alert = [[UIAlertView alloc]initWithTitle:#"UIAlertView" message:#"Record added" delegate:self cancelButtonTitle:#"OK" otherButtonTitles:nil];
[alert show];
[alert release];
alert = nil;
}
sqlite3_finalize(compiledStatement);
}
sqlite3_close(database);
}
[loginStatus release];
[connection release];
[webData release];
}
-(IBAction)click:(id)sender
{
[self sendRequest];
//this is to select username and password from database.
[self check];
}
this where i am passing then token id using for updat userprofile with tokinid but it not taken here it show error in console it show tokenid invalid i thing i have to pass user id also for update vale as refrence for tokenid
You should use the Delegate pattern for passing a value from one class to others.
See the below SO post.
How do I set up a simple delegate to communicate between two view controllers?