satya satya - 5 months ago 38
iOS Question

how to show messages and image in uitableviewcell in iOS

I am working on chat application. Actually i have 3 arrays. First array stores user name and second array stores chat message and third array stores images. I am picking image from photo gallery.

When user sends any message to the chat wall I display message in bubble.

So I'm writing some conditions like the below:


  • if
    arr2
    value is not null then displaying chat message

  • if
    arr3
    value is not null displaying image in chat bubble

  • if
    arr2
    value is
    null
    then i want to hide
    lbldesc
    and show only
    imv
    gallery image

  • if
    arr3
    value is
    null
    then hide imv gallery image and enable
    lblDesc



But i got exception like this:


Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '*** NSAllocateMemoryPages(4294967295) failed'`


Here is my code:

-(UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath

{

static NSString *CellIdentifier = @"cellIdentifier";

UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:nil];

if (cell == nil) {

cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier];

}

cell.selectionStyle=UITableViewCellSelectionStyleNone;

if (itemsDataArr.count>0) {

UIImageView *imgView = [[UIImageView alloc] initWithFrame:CGRectMake(35, 3, 250, 80)];

imgView.image = [UIImage imageNamed:@"speech-bubble-2-hi.png"];

imgView.layer.borderColor = [UIColor clearColor].CGColor;

imgView.tag = 5;

[cell.contentView addSubview:imgView];

NSArray *arr1=[[NSArray alloc]init];

arr1=[itemsUserNameArr objectAtIndex:indexPath.row];

NSString *strval=[arr1 objectAtIndex:0];

lblTitle=[[UILabel alloc]initWithFrame:CGRectMake(50, 5, 150, 20)];

lblTitle.highlightedTextColor=[UIColor whiteColor];

[cell.contentView addSubview:lblTitle];

[lblTitle setFont:[UIFont boldSystemFontOfSize:14]];

lblTitle.text=strval;

[imgView addSubview:lblTitle];

NSArray *arr2=[[NSArray alloc]init];

arr2=[itemsDataArr objectAtIndex:indexPath.row];

NSArray *arr3=[[NSArray alloc]init];

arr3=[itemImgArray objectAtIndex:indexPath.row];

if(![arr2 isEqual:@""])

{

NSString *strmsg=[arr2 objectAtIndex:0];

lblDesc=[[UILabel alloc]initWithFrame:CGRectMake(50, 22, 300, 20)];

lblDesc.highlightedTextColor=[UIColor whiteColor];

lblDesc.font=[UIFont systemFontOfSize:12.0];

[cell.contentView addSubview:lblDesc];

[lblDesc setHidden:NO];

lblDesc.text=strmsg;

[imgView addSubview:lblDesc];

// imv.hidden=YES;

// [imv setHidden:true];

}

arr3=[itemImgArray objectAtIndex:indexPath.row];

if(![arr3 isEqual:nil])

{

NSString *strImg=[arr3 objectAtIndex:0];

NSData *data = [[NSData alloc] initWithData:[NSData dataFromBase64String:strImg]];

//Now data is decoded. You can convert them to UIImage

imv = [[UIImageView alloc]initWithFrame:CGRectMake(93,12, 50, 50)];

imv.image=[UIImage imageWithData:data];

[imgView addSubview:imv];

[lblDesc setHidden:YES];

// lblDesc.hidden=YES;

}

}

return cell;

}

Answer

I've used PTSMessagingCell from here:

I've used messages array for texts/images. This is a ruf sample that may help you.

#import "ViewController.h"
#import "PTSMessagingCell.h"

@interface ViewController ()
{
    NSMutableArray *messages;
    UITextView *sendMsg;
    UITableView *chatTable;
}
@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
    messages = [[NSMutableArray alloc] initWithObjects:@"Hello",[UIImage imageNamed:@"download.jpeg"],@"Check This Out", nil];

    chatTable = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height-100)];
    chatTable.delegate = self;
    chatTable.dataSource = self;
    chatTable.separatorColor = [UIColor clearColor];
    [self.view addSubview:chatTable];
    chatTable.backgroundColor = [UIColor clearColor];


    sendMsg = [[UITextView alloc]initWithFrame:CGRectMake(0, chatTable.frame.size.height, self.view.frame.size.width-100, 100)];
    sendMsg.textColor = [UIColor blackColor];
    sendMsg.delegate = self;
    sendMsg.backgroundColor = [UIColor whiteColor];
    sendMsg.layer.cornerRadius = 3.0f;
    [self.view addSubview:sendMsg];

    UIButton *sendMsgbtn = [[UIButton alloc]initWithFrame:CGRectMake(sendMsg.frame.size.width, chatTable.frame.size.height, 100, 100)];
    [sendMsgbtn setTitle:@"SEND" forState:UIControlStateNormal];
    sendMsgbtn.backgroundColor = [UIColor redColor];
    [sendMsgbtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [sendMsgbtn addTarget:self action:@selector(sendClicked) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:sendMsgbtn];

    UITapGestureRecognizer *tapGestureRecognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapReceived:)];
    [tapGestureRecognizer setDelegate:self];
    [chatTable addGestureRecognizer:tapGestureRecognizer];
}

-(void)sendClicked{
    [sendMsg resignFirstResponder];
    [chatTable reloadData];
}

#pragma mark - TableView Delegate and DataSource Methods

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

    return [messages count];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    /*This method sets up the table-view.*/

    static NSString* cellIdentifier = @"messagingCell";
    PTSMessagingCell * cell = (PTSMessagingCell*) [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
    if (cell == nil) {
        cell = [[PTSMessagingCell alloc] initMessagingCellWithReuseIdentifier:cellIdentifier];
    }
    [self configureCell:cell atIndexPath:indexPath];
    return cell;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if ([[messages objectAtIndex:indexPath.row] isKindOfClass:[UIImage class]]) {
        return [(UIImage *)[messages objectAtIndex:indexPath.row] size].height;
    }
    else{
        const char *jsonString = [[NSString stringWithFormat:@"%@",[messages objectAtIndex:indexPath.row]] UTF8String];
        NSData *jsonData = [NSData dataWithBytes:jsonString length:strlen(jsonString)];
        NSString *goodMsg = [[NSString alloc] initWithData:jsonData encoding:NSNonLossyASCIIStringEncoding];
        CGSize messageSize = [PTSMessagingCell messageSize:goodMsg];
        NSLog(@"%f",messageSize.height + 2*[PTSMessagingCell textMarginVertical] + 40.0f);
        return messageSize.height + 2*[PTSMessagingCell textMarginVertical] + 40.0f;
    }

}

-(void)configureCell:(id)cell atIndexPath:(NSIndexPath *)indexPath {
    if (messages.count>0) {
        PTSMessagingCell* ccell = (PTSMessagingCell*)cell;

        if ([[messages objectAtIndex:indexPath.row] isKindOfClass:[UIImage class]]) {

            ccell.sent = YES;
            ccell.avatarImageView.image = [UIImage imageNamed:[messages objectAtIndex:indexPath.row]];
            ccell.messageLabel.text = @"";
        }
        else{
            ccell.sent = YES;

                            const char *jsonString = [[NSString stringWithFormat:@"%@",[messages objectAtIndex:indexPath.row]] UTF8String];
                            NSData *jsonData = [NSData dataWithBytes:jsonString length:strlen(jsonString)];
                            NSString *goodMsg = [[NSString alloc] initWithData:jsonData encoding:NSNonLossyASCIIStringEncoding];

            ccell.messageLabel.text = [messages objectAtIndex:indexPath.row];
        }
        ccell.timeLabel.text = [NSDateFormatter localizedStringFromDate:[NSDate date] dateStyle:NSDateFormatterShortStyle timeStyle:NSDateFormatterFullStyle];


        UITapGestureRecognizer *tapGestureRecognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapReceived:)];
        [tapGestureRecognizer setDelegate:self];
        [ccell addGestureRecognizer:tapGestureRecognizer];
    }
}

-(void)tapReceived:(UITapGestureRecognizer *)tapGestureRecognizer
{
    // do something, like dismiss your view controller, picker, etc., etc.
    [sendMsg resignFirstResponder];
}

Hope this helps.