how to pass tokenid from one class to other class in iphone - iphone

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?

Related

Once i get the alert i am not able to add the persons into my database

(void)addPersonButton:(id)sender {
char *error;
if (sqlite3_open([dbPathString UTF8String], &personDB) == SQLITE_OK) {
if ([nameField.text length] > 0 && [ageField.text length] > 0 ){
//{NSLog(#"mobile num %#", mobileNumField.text);
//NSCharacterSet *decimalSet = [NSCharacterSet decimalDigitCharacterSet];
//if ([mobileNumField.text rangeOfCharacterFromSet:decimalSet].location == NSNotFound) {
NSString *phoneNum = #"^(\\+91||0)?\\d{10}";
NSPredicate *test = [NSPredicate predicateWithFormat:#"SELF MATCHES %#", phoneNum];
BOOL matches = [test evaluateWithObject:[mobileNumField text]];
BOOL valid;
if (matches) {
sqlite3_stmt *statement;
NSString *querySQL = [NSString stringWithFormat:#"SELECT * FROM PERSONS"];
const char *query_sql = [querySQL UTF8String];
if (sqlite3_prepare(personDB, query_sql, -1, &statement, NULL) == SQLITE_OK) {
while (sqlite3_step(statement) == SQLITE_ROW) {
NSString *mobilenum = [[NSString alloc] initWithUTF8String:(const char *) sqlite3_column_text(statement, 3)];
NSLog(#"in DB: %# and in TF:%#", mobilenum, mobileNumField.text);
NSInteger len = [mobileNumField.text length];
NSLog(#"len %d",len);
// if (len > 10) {
NSInteger len1 = len - 10;
NSString *string = [mobileNumField.text substringWithRange:NSMakeRange(len1, 10)];
NSRange find = [mobilenum rangeOfString:string];
NSLog(#"find length %d",find.length);
//}
if (find.length) {
valid = false;
break;
}//else {NSLog(#"am in else");
valid = true;
//break;
//}
}NSLog(#"am out of while");
if (valid) {
NSLog(#"am inside valid if");
NSLog(#"%#", mobileNumField.text);
NSString *insertStmt = [NSString stringWithFormat:#"INSERT INTO PERSONS(NAME,AGE,MOBNUM) values ('%s','%d','%s')" ,[self.nameField.text UTF8String], [self.ageField.text intValue],[self.mobileNumField.text UTF8String]];
const char *insert_stmt = [insertStmt UTF8String];
NSLog(#"insertStmt=%# and insert_stmt = %s",insertStmt,insert_stmt);
int flag1 = (sqlite3_prepare(personDB, query_sql, -1, &statement, NULL) == SQLITE_OK);
int flag = (sqlite3_exec(personDB, insert_stmt, NULL, NULL, &error) == SQLITE_OK);
NSLog(#"flag1 = %d and flag = %d", flag1, flag);
if (flag) {
NSLog(#"Person Added");
Person *person = [[Person alloc] init];
[person setName:self.nameField.text];
[person setAge:[self.ageField.text intValue]];
[person setNumber:self.mobileNumField.text];
[arrayOfPersons addObject:person];
nameField.text = #"";
nameField.placeholder = #"Name ";
ageField.text = #"";
ageField.placeholder = #"Age";
mobileNumField.text = #"";
}else NSLog(#"person not added");
}
else {
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Error" message:#"Already registered with this mobile num" delegate:self cancelButtonTitle:#"Ok" otherButtonTitles: nil];
[alert show];
}
}
}
else {
UIAlertView *alert1 = [[UIAlertView alloc] initWithTitle:#"Error" message:#"Sorry, It's not valid mobile number. Please enter again" delegate:self cancelButtonTitle:#"ok" otherButtonTitles: nil];
[alert1 show];
}
}
else {
UIAlertView *alert2 = [[UIAlertView alloc] initWithTitle:#"Error" message:#"Name and Age fields are should not be empty" delegate:self cancelButtonTitle:#"Ok" otherButtonTitles:nil];
[alert2 show];
}
sqlite3_close(personDB);
}
}
In the above code am taking mobile number as a primary key, so whenever I registered with same mobile number then it shows the "alert" after getting the alert am giving another mobile number that is not registered before, at that time my SQL query (sqlite3_exec(personDB, insert_stmt, NULL, NULL, &error) == SQLITE_OK) is does not execute. I didn't understand why my SQL query is not executed. Please give me solution.
Did you enable ARC? if no did you release your Alert?
NSApplicationSupportDirectory is the one that works best for you, place your DB in NSApplicationSupportDirectory and then have access to the data from there and you can do insert and other operations. :)

updating table row using SQLite3

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.

Fast access to Core Data database information?

i have iOS application with core data, in one of my function i load the information to display one view of my application in this way:
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
NSEntityDescription *entity = [NSEntityDescription
entityForName:#"MyDate" inManagedObjectContext:managedObjectContext];
[fetchRequest setEntity:entity];
NSError *error;
NSArray *fetchedObjects = [managedObjectContext executeFetchRequest:fetchRequest error:&error];
for (NSManagedObject *info in fetchedObjects) {
if ([[[info valueForKey:#"status"] description] isEqualToString:#"Done"]) {
NSArray *allTask = [[info valueForKey:#"taskes"] allObjects];
for (NSManagedObject *task in allTask) {
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:#"yyyy-MM-dd"];
if (IsDateBetweenInclusive([task valueForKey:#"firstDate"], fromDate, toDate)) {
[taskArray addObject:task];
}
}
}
}
so i iterate all database to find the information and then display it, when the information in my database are few the method above is fast, but when the information in my database is more, on my 3GS take some seconds to display that view, instead in the simulator is fast, so my question is, there is a fast way, to take information from core date? i don't know there is a fast call with the attribute and the value i want retrieve from core data?
thanks
Use NSPredicate, see https://developer.apple.com/library/ios/#documentation/Cocoa/Conceptual/CoreData/Articles/cdFetching.html
The following piece of code will only fetch the values where the status field is set to 'Done'
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
NSEntityDescription *entity = [NSEntityDescription entityForName:#"MyDate" inManagedObjectContext:managedObjectContext];
[fetchRequest setEntity:entity];
[fetchRequest setPredicate:[NSPredicate predicateWithFormat:#"status == 'Done'"]];
NSError *error;
NSArray *fetchedObjects = [managedObjectContext executeFetchRequest:fetchRequest error:&error];
Create database:
NSString *docsDir;
NSArray *dirPaths;
dirPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
docsDir = [dirPaths objectAtIndex:0];
databasePath = [[NSString alloc] initWithString: [docsDir stringByAppendingPathComponent: #"newapp.sqlite"]];
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 LIST (id VARCHAR, title VARCHAR , description VARCHAR ,date VARCHAR)";
if ((sqlite3_exec(contactDB, sql_stmt, NULL, NULL, &errMsg) != SQLITE_OK) )
{
UIAlertView *alert=[[UIAlertView alloc]initWithTitle:#"Warning" message:#"Failed to create table" delegate:self cancelButtonTitle:#"OK" otherButtonTitles:nil];
[alert show];
}
sqlite3_close(contactDB);
} else {
UIAlertView *alert=[[UIAlertView alloc]initWithTitle:#"Warning" message:#"Failed to open/create database" delegate:self cancelButtonTitle:#"OK" otherButtonTitles:nil];
[alert show];
}
}
Insert values
NSString *id_str=#"21";
NSString *title=#"notisa";
NSString *description=#"new app";
NSString *date=#"21/4/30";
const char *dbpath = [databasePath UTF8String];
if (sqlite3_open(dbpath, &contactDB) == SQLITE_OK){
// error handling...
}
// Construct the query and empty prepared statement.
const char *sql = "INSERT INTO `LIST` (`id`,`title`,`description`,`date`) VALUES (?, ?, ?, ?)";
sqlite3_stmt *statement;
// UIImage *image = [UIImage imageWithData:imgdata];
//NSData *imageData=UIImagePNGRepresentation(image);
// Prepare the statement.
if (sqlite3_prepare_v2(contactDB, sql, -1, &statement, NULL) == SQLITE_OK) {
// Bind the parameters (note that these use a 1-based index, not 0).
sqlite3_bind_text(statement,1, [id_str UTF8String], -1, SQLITE_TRANSIENT);
sqlite3_bind_text(statement,2, [title UTF8String], -1, SQLITE_TRANSIENT);
sqlite3_bind_text(statement,3, [description UTF8String], -1, SQLITE_TRANSIENT);
sqlite3_bind_text(statement,4, [date UTF8String], -1, SQLITE_TRANSIENT);
}
// Execute the statement.
if (sqlite3_step(statement) != SQLITE_DONE) {
// error handling...
UIAlertView *alert=[[UIAlertView alloc]initWithTitle:#"Warning" message:#"Failed to Save" delegate:self cancelButtonTitle:#"OK" otherButtonTitles:nil];
[alert show];
}
else
{
UIAlertView *alert=[[UIAlertView alloc]initWithTitle:#"Database" message:#"Stored Successfully" delegate:self cancelButtonTitle:#"OK" otherButtonTitles:nil];
[alert show];
}
// Clean up and delete the resources used by the prepared statement.
sqlite3_finalize(statement);
sqlite3_close(contactDB);
Select Database:
const char *dbpath = [databasePath UTF8String];
sqlite3_stmt *statement;
if (sqlite3_open(dbpath, &contactDB) == SQLITE_OK)
{
NSString *querySQL = [NSString stringWithFormat: #"SELECT id,title,description,date FROM LIST"];
const char *query_stmt = [querySQL UTF8String];
if (sqlite3_prepare_v2(contactDB, query_stmt, -1, &statement, NULL) == SQLITE_OK)
{
while(sqlite3_step(statement) == SQLITE_ROW)
{
NSLog(#"ROW-->%d",SQLITE_ROW);
const char* policyNo = (const char *)sqlite3_column_text(statement, 1);
NSString *PolicyNumber = policyNo == NULL ? nil : [[NSString alloc]initWithUTF8String:policyNo];
NSLog(#"PolicyNumber:%#",PolicyNumber);
const char* start = (const char *)sqlite3_column_text(statement, 2);
NSString *startDate = start == NULL ? nil : [[NSString alloc]initWithUTF8String:start];
const char* end = (const char *)sqlite3_column_text(statement, 3);
NSString *endDate = end == NULL ? nil : [[NSString alloc]initWithUTF8String:end];
}
sqlite3_finalize(statement);
}
sqlite3_close(contactDB);
}
Delete :
const char *dbpath = [databasePath UTF8String];
sqlite3_stmt *statement;
if (sqlite3_open(dbpath, &contactDB) == SQLITE_OK)
{
NSString *querySQL = [NSString stringWithFormat: #"DELETE id,title,description,date FROM LIST"];
const char *query_stmt = [querySQL UTF8String];
if (sqlite3_prepare_v2(contactDB, query_stmt, -1, &statement, NULL) == SQLITE_OK)
{
while(sqlite3_step(statement) == SQLITE_ROW)
{
NSLog(#"ROW-->%d",SQLITE_ROW);
const char* policyNo = (const char *)sqlite3_column_text(statement, 1);
NSString *PolicyNumber = policyNo == NULL ? nil : [[NSString alloc]initWithUTF8String:policyNo];
NSLog(#"PolicyNumber:%#",PolicyNumber);
const char* start = (const char *)sqlite3_column_text(statement, 2);
NSString *startDate = start == NULL ? nil : [[NSString alloc]initWithUTF8String:start];
const char* end = (const char *)sqlite3_column_text(statement, 3);
NSString *endDate = end == NULL ? nil : [[NSString alloc]initWithUTF8String:end];
}
sqlite3_finalize(statement);
}
sqlite3_close(contactDB);
}

checking login and password in iphone

Hi i am trying to create a login and password for my app by using SQLite,, every thing is fine but the once the login button is pressed it is not entering in to home page!!!!
please find my code below:
-(void)checkindatabase{
NSArray *dirPath =NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *docDir =[dirPath objectAtIndex:0];
NSString *databasePath =[[NSString alloc] initWithString:[docDir stringByAppendingPathComponent:#"login.db"]];
if(sqlite3_open([databasePath UTF8String], &database) == SQLITE_OK)
{
NSLog(#"open");
NSString *sql = [[NSString alloc] initWithFormat:#"select * from UserInformation where Username='%#' and Password='%#'",loginName.text,password.text]; //[sql UTF8String];
//NSLog(#"'%s'",[sql UTF8String]);
sqlite3_stmt *statement;
if (sqlite3_prepare_v2(database, [sql UTF8String], -1, &statement, NULL) == SQLITE_OK)
{ if(sqlite3_step(statement) == SQLITE_ROW)
{
//user name is correct
//if u want to print in log use below code
homepage *hvc = [[homepage alloc]initWithNibName: nil bundle: nil];
hvc.modalTransitionStyle=UIModalTransitionStyleFlipHorizontal;
[self presentModalViewController:hvc animated: YES];
}
else {
UIAlertView* alert = [[UIAlertView alloc] initWithTitle:#"Login Failed!!!"
message:#"Check your PId and Password" delegate:nil
cancelButtonTitle:#"OK" otherButtonTitles:nil];
[alert show];
}}
sqlite3_finalize(statement);
}
sqlite3_close(database);
}
-(IBAction)homePage: (id)sender
{
[self checkindatabase];
}
Please find the code, as you asked.
-(BOOL)checkindatabase
{
NSArray *dirPath =NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *docDir =[dirPath objectAtIndex:0];
NSString *databasePath =[[NSString alloc] initWithString:[docDir stringByAppendingPathComponent:#"login.db"]];
if(sqlite3_open([databasePath UTF8String], &database) == SQLITE_OK)
{
NSLog(#"open");
NSString *sql = [[NSString alloc] initWithFormat:#"select * from UserInformation where Username='%#' and Password='%#'",loginName.text,password.text]; //[sql UTF8String];
//NSLog(#"'%s'",[sql UTF8String]);
sqlite3_stmt *statement;
if (sqlite3_prepare_v2(database, [sql UTF8String], -1, &statement, NULL) == SQLITE_OK)
{ if(sqlite3_step(statement) == SQLITE_ROW)
{
//user name is correct
//if u want to print in log use below code
return YES;
}
}
sqlite3_finalize(statement);
}
sqlite3_close(database);
return NO;
}
-(IBAction)homePage: (id)sender
{
if( [self checkindatabase] )
{
homepage *hvc = [[homepage alloc]initWithNibName: nil bundle: nil];
hvc.modalTransitionStyle=UIModalTransitionStyleFlipHorizontal;
[self presentModalViewController:hvc animated: YES];
[hvc release];
}
else
{
UIAlertView* alert = [[UIAlertView alloc] initWithTitle:#"Login Failed!!!"
message:#"Check your PId and Password" delegate:nil
cancelButtonTitle:#"OK" otherButtonTitles:nil];
[alert show];
[alert release];
}
}
As suggested by Aadhira...
Make checkindatabase with return type BOOL and return TRUE if Login successful and FALSE otherwise.
Then on the basis of BOOL value navigate to Home Page.
you cannot let other function to navigate the view, while performing IBAction method.
EDIT :
I am not looking to your database code.. i have simply shown you way how to use the BOOL return values.... Also mention errors if any you faced.
-(BOOL)checkindatabase{
NSArray *dirPath =NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *docDir =[dirPath objectAtIndex:0];
NSString *databasePath =[[NSString alloc] initWithString:[docDir stringByAppendingPathComponent:#"login.db"]];
if(sqlite3_open([databasePath UTF8String], &database) == SQLITE_OK)
{
NSLog(#"open");
NSString *sql = [[NSString alloc] initWithFormat:#"select * from UserInformation where Username='%#' and Password='%#'",loginName.text,password.text]; //[sql UTF8String];
//NSLog(#"'%s'",[sql UTF8String]);
sqlite3_stmt *statement;
if (sqlite3_prepare_v2(database, [sql UTF8String], -1, &statement, NULL) == SQLITE_OK)
{ if(sqlite3_step(statement) == SQLITE_ROW)
{
//user name is correct
//if u want to print in log use below code
flag = YES;
}
else {
UIAlertView* alert = [[UIAlertView alloc] initWithTitle:#"Login Failed!!!"
message:#"Check your PId and Password" delegate:nil
cancelButtonTitle:#"OK" otherButtonTitles:nil];
[alert show];
[alert release];
flag = NO;
}}
sqlite3_finalize(statement);
}
sqlite3_close(database);
return flag;
}
-(IBAction)homePage: (id)sender
{
BOOL newFlag = [self checkindatabase];
if(newFlag)
{
homepage *hvc = [[homepage alloc]initWithNibName: nil bundle: nil]
hvc.modalTransitionStyle=UIModalTransitionStyleFlipHorizontal;
[self presentModalViewController:hvc animated: YES];
}
}

How to save value single time in database in iphone

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;
}
}