获得多个表单数据

时间:2013-09-10 05:59:49

标签: iphone json nsdate nsurlconnection

我有多个用户的注册页面。当用户注册时,它将使用用户名和密码以多种形式数据存储到数据库。然后我进入viewcontroller与登录页面。当我使用username=abcd&password=123时它正常工作。但是,当我为多个用户使用username=%@&password=%@时,它无效。

代码:

NSString *post =[[NSString alloc] initWithFormat:@"username=%@&password=%@",[usrname text],[password text]];
NSLog(@"PostData: %@",post);

NSURL *url=[NSURL URLWithString:@"http://myserver.net/projects/mobile/test_login.php?name=abcd&password=123"];

NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];

NSString *postLength = [NSString stringWithFormat:@"%d", [postData length]];

NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setURL:url];
[request setHTTPMethod:@"POST"];

NSString *contentType = [NSString stringWithFormat:@"multipart/form-data"];
[request addValue:contentType forHTTPHeaderField: @"Content-Type"];

[request setValue:postLength forHTTPHeaderField:@"Content-Length"];
[request setValue:@"application/json" forHTTPHeaderField:@"Accept"];
[request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
[request setHTTPBody:postData];

NSError *error = [[NSError alloc] init];
NSHTTPURLResponse *response = nil;
NSData *urlData=[NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];

NSString *responseData = [[NSString alloc]initWithData:urlData encoding:NSUTF8StringEncoding];

NSLog(@"Response code: %d", [response statusCode]);

if ([responseData length]){
    NSLog(@"Response ==> %@", responseData);
    NSMutableDictionary *dict=[responseData JSONValue];
    NSInteger success = [(NSNumber *) [dict objectForKey:@"success"] integerValue];

    NSLog(@"%d",success);
        if(success == 1){
            //save the ID
            NSInteger id1 = [(NSNumber *) [dict objectForKey:@"id"] integerValue];
            NSUserDefaults *userData = [NSUserDefaults standardUserDefaults];
            [userData setInteger:id1 forKey:@"id"];
            [userData synchronize];

            NSLog(@"id1 data is %@",userData);

            NSLog(@"Login SUCCESS");
            [self alertStatus:@"Logged in Successfully." :@"Login Success!"];
            [self.navigationController pushViewController:overlay animated:YES];                        
        } else {
            NSString *error_msg = (NSString *) [dict objectForKey:@"error_message"];
            [self alertStatus:error_msg :@"Login Failed!"];
        }
    }

1 个答案:

答案 0 :(得分:1)

你应该这样试试

NSURL *url=[NSURL URLWithString:[NSString   stringWithFormat:@"http://myserver.net/projects/mobile/test_login.php?name=%@&password=%@",[usrname text],[password text]]];

希望它能帮到你,谢谢。 :)