How to distinguish between PNMessage sent by current user versus those from others?

StackOverflow https://stackoverflow.com//questions/24022502

  •  21-12-2019
  •  | 
  •  

Question

I am currently using PubNub to build chat-like functionality into an app. Following the example from the demo project, I added the following to my viewDidLoad to listen for messages received my channel:

[[PNObservationCenter defaultCenter] addMessageReceiveObserver:self withBlock:^(PNMessage *message) {
                                             NSLog(@"message %@", message);
                                             [self DisplayInLog: [NSString stringWithFormat:@"[%@]: %@",message.channel.name, message.message]];
                                             [self showReceivedMessage:message];
                                         }];

My problem is, when the current user sends a message using [PubNub sendMessage:text toChannel:self.currentChannel], the listener picks up on the message (as expected), but I am having trouble distinguishing from the PNMessage that which is sent by the current user and which is sent by someone else and picked up by the receiver. How should I go about approaching this without getting too hacky (for example, comparing the contents of the messages, when they were sent, etc).

Thanks!

Was it helpful?

Solution

@daspianist

You have to add field which will store identifier of the user and on client side check who is sender of the message by retrieving value from dictionary which will be send as message. For example:

[[PNObservationCenter defaultCenter] addMessageReceiveObserver:self withBlock:^(PNMessage *message) {

    NSLog(@"message %@", message);
    if (![[message.message valueForKey:@"sender"] isEqualToString:@"Bob"]) {

        [self DisplayInLog: [NSString stringWithFormat:@"[%@]: %@",message.channel.name, message.message]];
        [self showReceivedMessage:message];
    }
}];

[PubNub sendMessage:@{@"message":@"This is actual message which we want to send. It can be any Objective-C type.", @"sender":@"Bob"} toChannel:self.currentChannel];

In example above, it shouldn't process message if it has been sent from "Bob"

OTHER TIPS

SEND MESSAGE IN DICTIONARY

NSDictionary *message = [[NSDictionary alloc] initWithObjectsAndKeys:@"HELLLLOO",@"text",@"Kiran",@"sender", nil];
    [PubNub sendMessage:message toChannel:[PNDataManager sharedInstance].currentChannel
    withCompletionBlock:^(PNMessageState state, id object) {
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top