Search code examples
objective-cxcodeiconsbadgeread-unread

Displaying iOS badge number / Handling unread messages (xCode - OBJECTIVE-C)


I would like to update the inbox badge to display the number of unread messages (my messages don't self destruct, app is similar to iOS messages).

When the user clicks on a messages and goes back to the inbox tab the badge should be updated. Also, I would like to mark the background color of the unread cells differently than the cells of read...that way the user knows what has been read and what hasn't.

I have some working code but right now I am getting:

"Warning: A long-running operation is being executed on the main thread. Break on warnBlockingOperationOnMainThread() to debug."

This is the code I have for updating unread messages:

PFQuery *query = [PFQuery queryWithClassName:@"Messages"];
    [query whereKey:@"recipientIds" equalTo:[[PFUser currentUser] objectId]];
    [query orderByDescending:@"createdAt"];
    [query findObjectsInBackgroundWithBlock:^(NSArray *objects, NSError *error) {
        if (error) {
            NSLog(@"Error: %@ %@", error, [error userInfo]);
        } else {
            // messages were found!
            self.messages = objects;

            //find unread messages
            [query whereKey:@"readBy" notEqualTo:[[PFUser currentUser] objectId]];
            self.unreadMessages = [query findObjects];

            // set badge # to number of msgs
            if (self.unreadMessages.count > 0) {

                [[self navigationController] tabBarItem].badgeValue = [NSString stringWithFormat:@"%lu", (unsigned long)self.unreadMessages.count];
            }

            [self.tableView reloadData];

code for updating the cell:

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

PFObject *message = [self.messages objectAtIndex:indexPath.row];
cell.textLabel.text = [message objectForKey:@"senderEmail"];

if ([self.unreadMessages containsObject:message]) {
    // color background gray, bold the font
}else{
   // leave cell alone
}

Solution

  • [query findObjectsInBackgroundWithBlock:^(NSArray *objects, NSError *error)  
    {
        if (!error) 
        {
            self.unreadMessages = [NSMutableArray arrayWithArray:objects];
           // set badge # to number of msgs
            if (self.unreadMessages.count > 0) 
            { 
                [[self navigationController] tabBarItem].badgeValue = [NSString stringWithFormat:@"%lu", (unsigned long)self.unreadMessages.count];
            }
            [self.tableView reloadData];
        }
    }