如何从服务器数据库检查用户名和密码并在iPhone中显示新页面?

时间:2011-06-17 05:51:36

标签: iphone objective-c api sqlite

我有一个应用程序,其中我有一个由用户名和密码组成的登录表单。当用户输入用户名和密码时,他的用户名和密码应该从服务器api数据库验证,如果他是有效用户,他应该登录。

我已完成以下代码,通过服务器api数据库发布登录信息:

 -(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 
        {

        }

    }

在这个方法中,我正在解析从api服务器收到的JSON响应并绑定并插入到SQLite数据库中:

-(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"];
            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;
            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(journeyid,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, 2, [result.UserID UTF8String],-1,SQLITE_TRANSIENT);
                    sqlite3_bind_text(compiledStatement, 3, [result.DeviceInfoId UTF8String],-1,SQLITE_TRANSIENT);
                    sqlite3_bind_text(compiledStatement, 4, [txtUserName.text UTF8String],-1,SQLITE_TRANSIENT);
                    sqlite3_bind_text(compiledStatement, 5, [txtPassword.text UTF8String],-1,SQLITE_TRANSIENT);
                    sqlite3_bind_text (compiledStatement, 6, [result.FirstName UTF8String],-1,SQLITE_TRANSIENT);
                    sqlite3_bind_text (compiledStatement, 7, [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]; 
    }  

问题是我想当用户输入他/她的用户名和密码时,应该从服务器数据库验证用户名和密码,如果用户有效,则应该允许他登录。

1 个答案:

答案 0 :(得分:0)

更改您的JSON响应,使用其他一些密钥发送登录成功/失败的响应。使用

进行检查
NSString *loginres=[result valueForKey:@"LoginResponse"];

然后使用

进行验证
if([loginres isEqualToString:@"Success"]
{
  //Valid user
}
else
{
  //InValid user
}

如果身份验证失败,请将NSArray *values = [result objectForKey:@"Result"];设为NULL

然后检查

if(values!=NULL)
{
      //Valid user
}
else
{
      //InValid user
}