OGeek|极客世界-中国程序员成长平台

标题: ios - json解析期间的控制流 - Objective C [打印本页]

作者: 菜鸟教程小白    时间: 2022-12-12 22:38
标题: ios - json解析期间的控制流 - Objective C

我正在尝试创建一个必须输入用户名和密码的登录屏幕。单击登录按钮时,我将详细信息解析到服务器。这是代码

    NSString *post = [NSString stringWithFormat"username=%@&password=%@",[_userNameText text],[_passwordText text]];
    NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
    NSString *postLength = [NSString stringWithFormat"%lu" , (unsigned long)[postData length]];
    NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
    [request setURL:[NSURL URLWithString"http://*******/*****/******/userLogin.php"]];
    [request setHTTPMethod"OST"];
    [request setValue:postLength forHTTPHeaderField"sample data"];
    [request setHTTPBody:postData];

    NSURLSession *session = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
    [[session dataTaskWithRequest:request completionHandler:^(NSData *data , NSURLResponse *response , NSError *error){
        _requestReply = [[NSString alloc] initWithData:data encoding:NSASCIIStringEncoding];
        NSLog(@"%@",_requestReply);
    }] resume];

到目前为止,代码按预期工作。现在我想检查从服务器返回的“requestReply”是否具有“状态”键的值“成功”。所以我尝试用下面的代码打印它的值。

    _responseData = _requestReply;
    NSLog(@"%@" , _responseData[@"status"]);

这是控制台输出

2016-10-21 06:44:03.424 QuizApp2[65724:1287972] (null)
2016-10-21 06:44:03.501 QuizApp2[65724:1288003] {"status":"success","message":"Welcome admin","code":true}

我不确定,但我觉得代码的最后一行是在解析发生之前执行的。有人可以强调这里的控制流程吗?还是我的代码有什么问题?



Best Answer-推荐答案


我没有看到任何关于解析数据的代码。你是说这一行吗

_requestReply = [[NSString alloc] initWithData:data encoding:NSASCIIStringEncoding];

如果 userLogin.php 返回 JSON 数据,只需这样做:

[[session dataTaskWithRequest:request completionHandler:^(NSData *data , NSURLResponse *response , NSError *error){
    NSError *err = nil;
    id jsonData = [NSJSONSerialization JSONObjectWithData:data options:0 error:&err];
    if (err) {
        NSLog(@"%@", err);
    }
    else {
        NSLog(@"%@", jsonData[@"status"]);
    }
}] resume];

关于ios - json解析期间的控制流 - Objective C,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40167022/






欢迎光临 OGeek|极客世界-中国程序员成长平台 (http://sqlite.in/) Powered by Discuz! X3.4