2015-09-12 106 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 

    }); 
    }); 
}