使用响应json验证登录

时间:2016-09-15 04:17:21

标签: objective-c json login response nsurlconnection

如果登录响应是

,我想执行segue

登录回复:

  

{ “登录”:[{ “参数userid”: “12”, “名称”: “(ABC)”}]}

如何验证呢?

以下是我获取回复的代码。

-(IBAction)loginbutton:(id)sender {
    NSString *post = [[NSString alloc] initWithFormat:@"email==%@&pass==%@",self->email.text,self->passwrd.text];
    NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
    NSURL *url = [NSURL URLWithString:@"URL"];
    NSMutableURLRequest *theRequest = [NSMutableURLRequest requestWithURL:url];
    [theRequest setHTTPMethod:@"POST"];
    [theRequest setHTTPBody:postData];
    NSURLResponse *response;
    NSError *error;
    NSData *urlData = [NSURLConnection sendSynchronousRequest:theRequest returningResponse:&response error:&error];
    NSString *str=[[NSString alloc]initWithData:urlData encoding:NSUTF8StringEncoding]; NSLog(@"Login response: is %@",str); //getting response
}

1 个答案:

答案 0 :(得分:0)

NSString *post = [[NSString alloc] initWithFormat:@"email==%@&pass==%@",self->email.text,self->passwrd.text];
NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSURL *url = [NSURL URLWithString:@"URL"];
NSMutableURLRequest *theRequest = [NSMutableURLRequest requestWithURL:url];
[theRequest setHTTPMethod:@"POST"];
[theRequest setHTTPBody:postData];
NSURLResponse *response;
NSError *error;
NSData *urlData = [NSURLConnection sendSynchronousRequest:theRequest returningResponse:&response error:&error];
NSDictionary *jsondictionary = [NSJSONSerialization JSONObjectWithData:urlData options: NSJSONReadingMutableContainers error: &error];
NSLog(@"%@", jsondictionary);

输出将是:

{
     Login: [{
     userid: 12,
     name: (abc)
     }]
     }

获取用户详细信息请使用以下代码:

NSArray *userdetail = [jsondictionary objectForKey:@"Login"];
NSString *userID = [[userdetail firstObject]objectForKey:@"userid"];
NSLog(@"%@",userID);//12
NSString *userName = [[userdetail firstObject]objectForKey:@"name"];
NSLog(@"%@",userName);//(abc)