1

我的代码遇到问题,但我不确定它为什么会这样。它只是给我一个错误,说 JSON 错误。UITableView 永远不会被任何东西填满。我对 iOS 不是很有经验,因此感谢您提供任何帮助。

//
//  ViewController.m
//  Westmount Procrastinator
//
//  Created by Saleem on 10/25/13.
//  Copyright (c) 2013 Saleem Al-Zanoon. All rights reserved.
//

#import "ViewController.h"

@interface ViewController ()
@property (strong, nonatomic) IBOutlet UIWebView *webView;
@property (strong, nonatomic) IBOutlet UITableView *tableView;
@end

@implementation ViewController
- (void)viewDidLoad {
    [super viewDidLoad];
    NSString *fullURL = @"********";
    NSURL *url2 = [NSURL URLWithString:fullURL];
    NSURLRequest *requestObj = [NSURLRequest requestWithURL:url2];
    [_webView loadRequest:requestObj];

    self.title = @"News";

    [UIApplication sharedApplication].networkActivityIndicatorVisible = YES;

    NSURL *url = [NSURL URLWithString:@"****************"];
    NSURLRequest *request = [NSURLRequest requestWithURL:url];
    [NSURLConnection connectionWithRequest:request delegate:self];    //  NSString * urlString = [NSString stringWithFormat:@"http://salespharma.net/westmount/get_all_products.php"];
  //  NSURL * url = [NSURL URLWithString:urlString];
 //   NSData * data = [NSData dataWithContentsOfURL:url];
 //   NSError * error;
//    NSMutableDictionary *json = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error];
//    NSLog(@"%@",json);
}
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
    data = [[NSMutableData alloc] init];
}

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)theData
{
    [data appendData:theData];
}

- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
    [UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
    NSArray *responseDict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:NULL];
    //news = [responseDict objectAtIndex:0];
    // [mainTableView reloadData];
    if ([responseDict isKindOfClass:[NSArray class]]) {
        news = responseDict;
        [mainTableView reloadData];
    } else {
        // Looks like here is some part of the problem but I don't know why.
        NSLog(@"JSON Error.");

        UIAlertView *errorView = [[UIAlertView alloc] initWithTitle:@"Error" message:@"Could not contact server!" delegate:nil cancelButtonTitle:@"Dismiss" otherButtonTitles:nil];
        [errorView show];

    }
}

- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
    UIAlertView *errorView = [[UIAlertView alloc] initWithTitle:@"Error" message:@"The download could not complete - please make sure you're connected to either 3G or Wi-Fi." delegate:nil cancelButtonTitle:@"Dismiss" otherButtonTitles:nil];
    [errorView show];
    [UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
}

- (int)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

- (int)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return [news count];
}

NSString *_getString(id obj)
{
    return [obj isKindOfClass:[NSString class]] ? obj : nil;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"Cell"];

    if(cell == nil){
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:@"Cell"];
    }

    cell.textLabel.text = _getString([[news objectAtIndex:indexPath.row] objectForKey:@"Issue"]);
    cell.detailTextLabel.text = _getString([[news objectAtIndex:indexPath.row] objectForKey:@"Name"]);

    return cell;
}
   @end

JSON 在 Internet 上的外观:

    {

   "Issues":[
      {
         "Issue":"2",
         "Link":"google.com",
         "Name":"Ios Test"
      },
      {
         "Issue":"3",
         "Link":"Yahoo",
         "Name":"iOS test 2"
      }
   ],
   "success":1
}

编辑:抱歉在我的问题中不清楚,该应用程序不会崩溃,但无法将数据加载到它放置的日志中的数据库中:

2013-10-26 10:26:41.670 Westmount Procrastinator[2490:70b] JSON Error.
2013-10-26 10:26:41.671 Westmount Procrastinator[2490:70b] Server Data: 
{"Issues":[{"Issue":"2","Link":"google.com","Name":"Ios Test"}],"success":1}

联系数据库的应用程序的目标是下载一份报纸的问题列表,然后在列表视图中列出它们。然后允许用户单击问题并下载它们。

编辑我在 JSON 中添加了更多内容以帮助解释。

4

2 回答 2

3

从您的示例 JSON 结构来看,它似乎不是 NSArray。它是 NSDictionary 。因此,在解析 JSON 数据时,将其保存在 NSDictionary 而不是 NSArray 中。此外,之后更改您的 IF 条件。

重要的是,如果您的表视图正在从 NSDictionaries 的 NSArray 中读取数据,那么我会说将此 NSDictionary 放入 NSArray 并将其传递给表视图。此外,从服务器端检查输出是什么,以防它们是您需要相应处理的多个字典。所以基本上你需要在这里引入更多的行,否则在所有情况下都要求数据提供者(服务器端)发送 NSArray。

NSDictionary *responseDict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:NULL];
if ([responseDict isKindOfClass:[NSDictionary class]]) {
    NSArray *tableArray = [NSArray arrayWithArray:responseDict[@"Issues"]];
}

现在使用 tableArray 来填充您的表格。

于 2013-10-26T17:29:55.397 回答
0

Issues 是一个字典数组,因此您应该在 处请求字典indexpath.row,然后使用objectForKey从该字典中提取适当的值。

    NSDictionary *myDict = @{@"Issues": @[@{@"Issue": @"2",
                                            @"Link": @"google.com",
                                            @"Name": @"Ios Test"},
                                          @{@"Issue": @"3",
                                            @"Link": @"Yahoo",
                                            @"Name": @"iOS test 2"}],
                             @"success": @"1"};

    NSArray *issues = [myDict objectForKey:@"Issues"];

    [issues enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
        NSLog(@"Issue: %@ Link: %@ Name: %@", [obj objectForKey:@"Issue"], [obj objectForKey:@"Link"], [obj objectForKey:@"Name"]);
    }];

将返回:

2013-10-26 16:42:43.572 Jsontest[43803:303] Issue: 2 Link: google.com Name: Ios Test
2013-10-26 16:42:43.573 Jsontest[43803:303] Issue: 3 Link: Yahoo Name: iOS test 2
于 2013-10-26T20:43:18.907 回答