English 中文(简体)
如何节省电话数据库中的单值时间
原标题: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;
    }
}
最佳回答

它非常简单。 首先从Sqlite数据库获得用户Name和所有与用户有关的数值,以掌握提交年份。 如果所有数值都为零,那么你就开始服务器程序。 如果数据库中的所有数值都直接用于下一次应用筛选。

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

我希望大家现在能够理解。

<>>>>>

-(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;
    }
}
问题回答

暂无回答




相关问题
sqlite3 is chopping/cutting/truncating my text columns

I have values being cut off and would like to display the full values. Sqlite3 -column -header locations.dbs " select n.namelist, f.state, t.state from names n left join locations l on l.id = n.id ...

Entity Framework with File-Based Database

I am in the process of developing a desktop application that needs a database. The application is currently targeted to SQL Express 2005 and works wonderfully. However, I m not crazy about having ...

Improve INSERT-per-second performance of SQLite

Optimizing SQLite is tricky. Bulk-insert performance of a C application can vary from 85 inserts per second to over 96,000 inserts per second! Background: We are using SQLite as part of a desktop ...

Metadata for columns in SQLite v2.8 (PHP5)

How can I get metadata / constraints (primary key and "null allowed" in particular) for each column in a SQLite v2.8 table using PHP5 (like mysql_fetch_field for MySql)? sqlite_fetch_column_types (OO:...

SQLite , Derby vs file system

I m working on a Java desktop application that reads and writes from/to different files. I think a better solution would be to replace the file system by a SQLite database. How hard is it to migrate ...

热门标签