试图在聊天应用程序中从JSON文件填充TableView?

时间:2014-08-12 16:44:20

标签: ios json uitableview

我正在使用聊天应用模板,我已将其集成到我的主应用中。我希望表中的每一行都显示来自json文件的数据,以便向用户显示聊天室名称和房间的详细信息,但可以按照我的意愿进行更改,而无需每次都将应用程序重新提交给apple。

而不是把完整的代码放在这里,它真的很长,所以我把它Here编辑:它现在也在下面。

此外,不是删除原始代码(因为例如房间名称已经在应用程序中指定),我已经将其评分出来,因此您不会猜测我从原始模板中做了哪些更改。

最后,我的问题......当我运行应用程序时,数据会显示我想从tableview中的JSON文件中获取它的方式,但是当选择一行时,应用程序崩溃而不是让用户进入聊天室。

我在解决这个问题方面处于领先地位,我已经尝试在这里搜索并使用我能想到的每个术语来解决它。

我在控制台中收到的错误消息是:

2014-08-13 09:27:23.708 Huddle [6073:60b] - [__ NSCFDictionary stringByTrimmingCharactersInSet:]:无法识别的选择器发送到实例0x17e85350

我想发布截图,但这不允许我 - 所以将其上传到我的网络服务器 - Here(如果不允许,请不要再次暂停此问题,只是给我发电子邮件&我将立即删除图像的链接,我只是想提供我能提供的所有信息。

万分感谢百万提供任何帮助!

编辑:网站管理员需要此问题中的完整代码,因此请进行修改以添加:

    #import "ProgressHUD.h"
    #import <Firebase/Firebase.h>
    #import <FirebaseSimpleLogin/FirebaseSimpleLogin.h>

    #import "common.h"
    #import "utilities.h"

    #import "MenuViewController.h"
    #import "LoginViewController.h"
    #import "ChatViewController.h"


    @interface MenuViewController()
    {
NSDictionary *userinfo;
NSMutableArray *items;
NSURL *url;


UIBarButtonItem *buttonLogin;
UIBarButtonItem *buttonLogout;
    }
    @end


    @implementation MenuViewController


    - (void)viewDidLoad

    {


[super viewDidLoad];
self.title = @"Chat";

userinfo = nil;

// Allocate Memory for the raw JSON Dictionary, and for just the tv episodes.
userinfo = [[NSDictionary alloc] init];
items = [[NSMutableArray alloc] init];

// Setup the URL with the JSON URL.
url = [NSURL URLWithString:@"http://mackuk.co.uk/chat.json"];

[self parseJSONWithURL:url];

/*ORIGINAL CHAT ROOM NAMES

 items = [[NSMutableArray alloc] init];
[items addObject:@"Room 1"];
[items addObject:@"Room 2"];
*/

buttonLogin = [[UIBarButtonItem alloc] initWithTitle:@"Login" style:UIBarButtonItemStyleBordered target:self action:@selector(actionLogin)];
buttonLogout = [[UIBarButtonItem alloc] initWithTitle:@"Logout" style:UIBarButtonItemStyleBordered target:self action:@selector(actionLogout)];

[self checkAuthStatus];



    }

    - (void) parseJSONWithURL:(NSURL *) jsonURL
    {
        // Set the queue to the background queue. We will run this on the background thread to keep
// the UI Responsive.
dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0);

[UIApplication sharedApplication].networkActivityIndicatorVisible = YES;

// Run request on background queue (thread).
dispatch_async(queue, ^{
    NSError *error = nil;

    // Request the data and store in a string.
    NSString *json = [NSString stringWithContentsOfURL:jsonURL
                                              encoding:NSASCIIStringEncoding
                                                 error:&error];
    if (error == nil){

        // Convert the String into an NSData object.
        NSData *jsonData = [json dataUsingEncoding:NSASCIIStringEncoding];

        // Parse that data object using NSJSONSerialization without options.
        userinfo = [NSJSONSerialization JSONObjectWithData:jsonData options:kNilOptions error:&error];

        // Parsing success.
        if (error == nil)
        {
            dispatch_async(dispatch_get_main_queue(), ^{
                [UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
                items = [[userinfo valueForKey:@"Chat"] valueForKey:@"rooms"];
                [self.tableView reloadData];
            });
        }

        // Parsing failed, display error as alert.
        else
        {
            UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"Error!" message:@"Uh Oh, Parsing Failed." delegate:nil cancelButtonTitle:@"Dismiss" otherButtonTitles:nil];

            [alertView show];
        }
    }

    // Request Failed, display error as alert.
    else
    {
        UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"Error!" message:@"Request Error! Check that you are connected to wifi or 3G/4G with internet access." delegate:nil cancelButtonTitle:@"Dismiss" otherButtonTitles:nil];

        [alertView show];
    }
});
    }


    - (void)showError:(id)message

    {
[ProgressHUD showError:message Interacton:NO];
    }


    - (void)checkAuthStatus

    {
[ProgressHUD show:@"Please wait..." Interacton:NO];

Firebase *ref = [[Firebase alloc] initWithUrl:FIREBASE];
FirebaseSimpleLogin *authClient = [[FirebaseSimpleLogin alloc] initWithRef:ref];
[authClient checkAuthStatusWithBlock:^(NSError *error, FAUser *user)
{
    if (error == nil)
    {
        [ProgressHUD dismiss];

        if (user != nil)
        {
            userinfo = ParseUserData(user.thirdPartyUserData);
            self.navigationItem.rightBarButtonItem = buttonLogout;
        }
        else self.navigationItem.rightBarButtonItem = buttonLogin;
    }
    else
    {
        NSString *message = [error.userInfo valueForKey:@"NSLocalizedDescription"];
        [self performSelectorOnMainThread:@selector(showError:) withObject:message waitUntilDone:NO];
    }
}];
    }


    - (void)actionLogin

    {
LoginViewController *loginViewController = [[LoginViewController alloc] init];
loginViewController.delegate = self;

UINavigationController *navController = [[UINavigationController alloc] initWithRootViewController:loginViewController];
navController.navigationBar.translucent = NO;
navController.navigationBar.barTintColor = COLOR_TITLE;
navController.navigationBar.tintColor = COLOR_TITLETEXT;
navController.navigationBar.titleTextAttributes = @{NSForegroundColorAttributeName:COLOR_TITLETEXT};
[self presentViewController:navController animated:YES completion:nil];
    }


    - (void)didFinishLogin:(NSDictionary *)Userinfo

    {
userinfo = [Userinfo copy];
self.navigationItem.rightBarButtonItem = buttonLogout;
    }


    - (void)actionLogout

    {
Firebase *ref = [[Firebase alloc] initWithUrl:FIREBASE];
FirebaseSimpleLogin *authClient = [[FirebaseSimpleLogin alloc] initWithRef:ref];
[authClient logout];

userinfo = nil;
self.navigationItem.rightBarButtonItem = buttonLogin;
    }

    #pragma mark - Table view data source


    - (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView

    {
return 1;
    }

    - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section

    {

return [items count];
    }


    - (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 = [[items objectAtIndex:indexPath.row] objectForKey:@"name"];
NSNumber *seasonNum = [[items objectAtIndex:indexPath.row] objectForKey:@"detail"];
NSNumber *episodeNum = [[items objectAtIndex:indexPath.row] objectForKey:@"kotime"];
NSMutableString *seasonEpisodeNum = [NSMutableString stringWithFormat:@" %@ ", seasonNum];
[seasonEpisodeNum appendString:[NSMutableString stringWithFormat:@" %@", episodeNum]];
cell.detailTextLabel.text = seasonEpisodeNum;

return cell;




/* ORIGINAL CELL INFO

 UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell"];
if (cell == nil) cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:@"cell"];

cell.textLabel.text = [items objectAtIndex:indexPath.row];



return cell;*/
    }

    #pragma mark - Table view delegate


    - (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath

    {
[tableView deselectRowAtIndexPath:indexPath animated:YES];

if (userinfo != nil)
{
    NSString *chatroom = [items objectAtIndex:indexPath.row];
    ChatViewController *chatViewController = [[ChatViewController alloc] initWith:chatroom Userinfo:userinfo];
    self.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:chatViewController animated:YES];
    self.hidesBottomBarWhenPushed=NO;
}
else [self actionLogin];
    }

    #pragma mark iAd Delegate Methods


    -(void)bannerViewDidLoadAd:(ADBannerView *)banner {

[UIView beginAnimations:nil context:nil];
[UIView setAnimationDuration:1];
[banner setAlpha:1];
[UIView commitAnimations];

    }

    -(void)bannerView:(ADBannerView *)banner didFailToReceiveAdWithError:(NSError *)error {

[UIView beginAnimations:nil context:nil];
[UIView setAnimationDuration:1];
[banner setAlpha:0];
[UIView commitAnimations];

    }

    @end

0 个答案:

没有答案