2015-03-13 67 views
-1

我有一些代碼使用Dribbble API來返回一個Shot,但是,如果JSON中的任何數據是空的,應用崩潰,我試圖實現並捕獲,如果它是null繼續前進,但這似乎不起作用。請有人建議?JSON返回空崩潰應用

非常感謝

詹姆斯

self.JSONString = [NSString stringWithFormat:@"http://api.dribbble.com/shots/1970521"]; 
NSURLRequest *request = [[NSURLRequest alloc] initWithURL:[NSURL URLWithString:self.JSONString]]; 

__block NSDictionary *json; 
[NSURLConnection sendAsynchronousRequest:request 
            queue:[NSOperationQueue mainQueue] 
         completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) { 
          if (data != nil) { 
           json = [NSJSONSerialization JSONObjectWithData:data 
                     options:0 
                     error:nil]; 
           NSLog(@"Async JSON: %@", json); 
          } 
          else { 
           return; 
          } 
         }]; 
+0

在處理'null'的'json'後,您的應用必須崩潰。解決方法是[NSJSONSerialization JSONObjectWithData:data options:0 error:nil];無法解析您的數據,原因可能是傳遞給它的非UTF數據。 – iphonic 2015-03-13 10:31:59

+0

/questions/5716942/touchjson-dealing-with-nsnull – Wain 2015-03-13 10:31:59

+0

您應該將XCode調試器附加到您的應用程序併發布崩潰回溯,否則很難爲您提供幫助。拋出異常嗎?它是什麼樣的崩潰? – Bensge 2015-03-13 10:36:10

回答

1

您需要妥善處理連接錯誤。 嘗試類似這樣:

self.JSONString = [NSString stringWithFormat:@"http://api.dribbble.com/shots/1970521"]; 
NSURLRequest *request = [[NSURLRequest alloc] initWithURL:[NSURL URLWithString:self.JSONString]]; 

__block NSDictionary *json; 
[NSURLConnection sendAsynchronousRequest:request 
    queue:[NSOperationQueue mainQueue] 
    completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) 
    { 
     if (connectionError != nil || data == nil) 
     { 
      NSLog(@"Error loading dribble shot: %@",connectionError); 
      //TODO: Show an alert to the user with UIAlertView? 
     } 
     else 
     { 
      NSError *jsonParsingError = nil; 
      json = [NSJSONSerialization JSONObjectWithData:data options:0 error:&jsonParsingError]; 
      if (jsonParsingError != nil || json == nil){ 
       NSLog(@"Error parsing JSON: %@",jsonParsingError); 
       //TODO: User alert? 
      } 
      else 
      { 
       NSLog(@"Parsed JSON: %@",json); 
       //Process parsed JSON, update UI, etc. 
       //Keep in mind updates to the UI should be done in a main-thread call like this: 
       dispatch_sync(dispatch_get_main_queue(),^{ 
        //Update UI here 
       }); 
      } 
     } 
    } 
}];