2015-09-12 108 views
1

我有一个iOS应用程序,用户在使用该应用程序之前必须注册。我在Storyboard中创建了UI,并且正在从UITextfields读取用户详细信息。然后我将详细信息发送给注册API,该API返回JSON响应。我正在使用NSURLConnection进行通信。NSURLConnection返回的JSON数据

这里是我从测试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文件,当有人点击注册按钮,我创建了请求,并启动连接如下。我给一个虚拟的URL例子,但我收到的回应是: {“用户名”:“汉斯”,“密码”:“汉斯”}

- (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

enter image description here

在此先感谢。

回答

2

您的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方法。当然必须删除。

+0

我尝试和初始化*字典时得到警告。警告:“不兼容的指针类型使用nsstring类型的表达式初始化nsdictionary”然后应用程序在行崩溃:“NSString * test = [dictionary objectForKey:@”password“];”与错误:“ - [__ NSCFString objectForKey:]:无法识别的选择器发送到实例” – heyred

+0

你在哪里登录行“JSON字符串...”。实际上,日志文本是字典的字符串表示形式。或者,收到的JSON字符串是否包含超过用户名/密码信息? – vadian

+0

PS:我编辑了这篇文章,看看'编辑'加法。 – vadian

1

你的代码有2个问题:

  1. 要转换JSON服务器响应的NSString。
  2. 你的JSON数据确实是一个NSDictionary。

这必须解决您的问题:

- (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 

    }); 
    }); 
}