• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

ios - json解析期间的控制流 - Objective C

[复制链接]
菜鸟教程小白 发表于 2022-12-12 22:38:59 | 显示全部楼层 |阅读模式 打印 上一主题 下一主题

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

    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/

回复

使用道具 举报

懒得打字嘛,点击右侧快捷回复 【右侧内容,后台自定义】
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

关注0

粉丝2

帖子830918

发布主题
阅读排行 更多
广告位

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap