在NSURLConnection上返回的JSON数据

嘿嘿

我有一个iOS应用程序,用户必须先注册才能使用该应用程序。我已经在Storyboard中创建了UI,并且正在从UITextfields中读取“用户”详细信息。然后,我将详细信息发送到Register API,后者将发送回JSON响应。我正在使用NSURLConnection进行通信。

这是我从测试URL收到的响应-仅供测试:{“用户名”:“汉斯”,“密码”:“汉斯”}

但是,当我尝试读取密码以确保该用户不存在时(再次,仅出于测试目的),我将返回nil作为密码值返回。

在我的.h文件中,我声明了数据和连接:

@interface RegisterViewController : UIViewController <NSURLConnectionDataDelegate>
{
    // Conform to the NSURLConnectionDelegate protocol and declare an instance variable to hold the response data
    NSMutableData *buffer;
    NSURLConnection *myNSURLConnection;
}

在我的.m文件中,当有人单击REGISTER按钮时,我将创建请求并按如下所示启动连接。我在示例中提供了一个虚拟URL,但是我收到的响应是:{“ username”:“ Hans”,“ password”:“ Hans”}

- (IBAction)registerButtonClicked:(id)sender
{
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"http://myDummyURL/Login.php"]];

    // Construct the JSON Data
    NSDictionary *stringDataDictionary = @{@"firstname": firstname, @"lastname": lastname, @"email": email, @"password" : password, @"telephone" : telephone};
    NSError *error;
    NSData *requestBodyData = [NSJSONSerialization dataWithJSONObject:stringDataDictionary options:0 error:&error];

    // Specify that it will be a POST request
    [request setHTTPMethod:@"POST"];

    // Set header fields
    [request setValue:@"text/plain" forHTTPHeaderField:@"Accept"];
    [request setValue:@"application/json; charset=utf-8" forHTTPHeaderField:@"Content-Type"];

    //NSData *requestBodyData = [stringData dataUsingEncoding:NSUTF8StringEncoding];
    [request setHTTPBody:requestBodyData];

    myNSURLConnection = [NSURLConnection connectionWithRequest:request delegate:self];

    // Ensure the connection was created
    if (myNSURLConnection)
    {
        // Initialize the buffer
        buffer = [NSMutableData data];

        // Start the request
        [myNSURLConnection start];
    }
}

此处创建连接没有问题。

在我的.m文件中,我实现了委托方法,在connectionDidFinishLoading()中,我尝试读取返回的JSON。下面是我为此使用的代码。

- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
    // Dispatch off the main queue for JSON processing
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{

        NSError *error = nil;
        NSString *jsonString = [[NSJSONSerialization JSONObjectWithData:buffer options:0 error:&error] description];

        // Dispatch back to the main queue for UI
        dispatch_async(dispatch_get_main_queue(), ^{

            // Check for a JSON error
            if (!error)
            {
                NSError *error = nil;
                NSArray *jsonArray = [NSJSONSerialization JSONObjectWithData:[jsonString dataUsingEncoding:NSUTF8StringEncoding] options:NSJSONReadingMutableContainers error:&error];
                NSDictionary *dictionary = [jsonArray objectAtIndex:0];
                NSString *test = [dictionary objectForKey:@"password"];
                NSLog(@"Test is: %@", test);
            }
            else
            {
                NSLog(@"JSON Error: %@", [error localizedDescription]);
            }

            // Stop animating the Progress HUD

        });
    });
}

在下面的日志屏幕抓取中,您可以看到返回的jsonString具有值,但是jsonArray始终为nil。错误读取:error NSError *域:@“ NSCocoaErrorDomain”-代码:3840 0x00007ff158498be0

在此处输入图片说明

提前致谢。

瓦迪安

jsonString其实是在NSDictionary目标-创建人NSJSONSerialization-你要找的,不存在数组。在JSON字符串中,花括号{}代表字典,方括号[]代表数组

尝试这个

- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
  // Dispatch off the main queue for JSON processing
  dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{

    NSError *error = nil;
    NSDictionary *dictionary = [NSJSONSerialization JSONObjectWithData:buffer options:0 error:&error];

    // Dispatch back to the main queue for UI
    dispatch_async(dispatch_get_main_queue(), ^{

        // Check for a JSON error
        if (!error)
        {
            NSString *test = [dictionary objectForKey:@"password"];
            NSLog(@"Test is: %@", test);
        }
        else
        {
            NSLog(@"JSON Error: %@", [error localizedDescription]);
        }

        // Stop animating the Progress HUD

    });
  });
}

编辑:我忽略了descriptionNSJSONSerialization末尾方法当然必须删除。

本文收集自互联网,转载请注明来源。

如有侵权,请联系[email protected] 删除。

编辑于
0

我来说两句

0条评论
登录后参与评论

相关文章

来自分类Dev

从nsurlconnection委托方法返回响应数据

来自分类Dev

NSURLConnection ExpectedContentLength返回-1

来自分类Dev

NSURLConnection委托返回Null

来自分类Dev

使用NSURLConnection检索数据

来自分类Dev

处理返回的JSON数据

来自分类Dev

如何返回json数据

来自分类Dev

从ajax返回数据json

来自分类Dev

Coldfusion返回JSON数据

来自分类Dev

使用“数据”返回JSON数据

来自分类Dev

NSURLConnection获取JSON文件

来自分类Dev

cq5不在'... infinity.json'请求上返回子页面json数据

来自分类Dev

在Angular Response上返回json

来自分类Dev

使用AngularJS获取JSON数据并在返回的对象上添加方法

来自分类Dev

在Doctrine结果上使用jsonModel返回JSON数据时得到空响应-特殊字符编码问题

来自分类Dev

使用AngularJS获取JSON数据并在返回的对象上添加方法

来自分类Dev

从vb.net中json文件上的数组返回多个元素,绑定到数据表

来自分类Dev

访问从CMS返回的JSON数据

来自分类Dev

用php返回json数据

来自分类Dev

在json对象中返回数据

来自分类Dev

在Json中返回数据LINQ

来自分类Dev

获取json返回数据的值

来自分类Dev

访问从CMS返回的JSON数据

来自分类Dev

jQuery菜单-返回JSON数据

来自分类Dev

JSON数组未返回数据

来自分类Dev

HTML返回而不是JSON数据

来自分类Dev

访问SendGrid返回的JSON数据

来自分类Dev

JSON 请求未返回数据

来自分类Dev

Json API 不返回数据

来自分类Dev

RPlumber API-以CSV而不是JSON格式返回数据-在Mac上本地工作,但在ubuntu-16.04上不工作