JSON数据在NSURLConnection上返回
我有一个iOS应用程序,用户必须先注册才能使用该应用程序。 我在Storyboard中创建了UI,并且正在从UITextfields读取用户详细信息。 然后我将详细信息发送给注册API,该API返回JSON响应。 我正在使用NSURLConnection进行通信。
以下是我从测试网址收到的回复 - 仅用于测试目的: {“username”:“Hans”,“password”:“Hans”}
但是,当我尝试读取密码以确保用户不存在(再次,仅用于测试目的)时,我返回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文件中,当有人点击注册按钮时,我创建请求并按如下所示启动连接。 我在示例中给出了一个虚拟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始终为零。 该错误读取:错误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
    });
  });
}
  编辑:我忽略了NSJSONSerialization行末尾的description方法。  当然必须删除。 
你的代码有两个问题:
这必须解决您的问题:
- (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
    });
  });
}
上一篇: JSON Data returned on NSURLConnection
下一篇: NSURLConnection causing memory warning while downloading large portion of data
