【问题标题】:iOS XMPP received message in conversation screeniOS XMPP 在对话屏幕中收到消息
【发布时间】:2015-06-15 12:05:43
【问题描述】:

我正在开发基于 XMPP 的项目。我可以发送消息,它会显示在对话屏幕中,但是当我收到消息时,它只会显示在警报视图中,而无法在对话屏幕中看到。

 - (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view.

[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(messageReceived:) name:MessageRecivedNotif object:nil];

appdelegate=(AppDelegate*)[[UIApplication sharedApplication] delegate];
[self getAllMessagesArrayWithOppositeUser:_jid];

[[NSNotificationCenter defaultCenter] addObserver:self
                                         selector:@selector(keyboardWasShown:)
                                             name:UIKeyboardDidShowNotification
                                           object:nil];


}

#pragma mark table delegate and datasource methods
 - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return data.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
UITableViewCell *cell = [tblobj dequeueReusableCellWithIdentifier:@"cell"];
UILabel *lbl;
if (cell==nil)
{
    cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"cell"];

    if (chatLblRight == 1)
    {
        lbl = [[UILabel alloc]initWithFrame:CGRectMake(200, 10, 150, 44)];
        [lbl setTextColor:[UIColor redColor]];
        [cell.contentView   addSubview:lbl];
    }


 }
 if (chatLblRight == 1)
 {
    lbl.text = [[data objectAtIndex:indexPath.row]valueForKey:@"text"];
    chatLblRight = 0;
    lbl = [[UILabel alloc]initWithFrame:CGRectMake(200, 10, 150, 44)];
    [lbl setTextColor:[UIColor redColor]];
    [cell.contentView   addSubview:lbl];

    return cell;
  }
  else
  {
    cell.textLabel.text=[[data objectAtIndex:indexPath.row]valueForKey:@"text"];
    return cell;
  }
}
-(void)messageReceived:(NSNotification*)notif
{
XMPPMessage *message=(XMPPMessage*)notif.object;
NSString *body = [[message elementForName:@"body"] stringValue];
NSMutableDictionary *dic_recive = [[NSMutableDictionary alloc]init];
[dic_recive setObject:body forKey:@"text"];
[data addObject:dic_recive];
chatLblRight = 1;
[tblobj reloadData];
}
 -(IBAction)btnsend:(id)sender
{
[txtmsg resignFirstResponder];
[UIView beginAnimations:nil context:nil];
[UIView setAnimationDuration:0.2];
[msgview setFrame:CGRectMake(0, self.view.bounds.size.height-53, self.view.bounds.size.width, 53)];
[UIView commitAnimations];
[((AppDelegate*)[[UIApplication sharedApplication]delegate]) sendMessage:txtmsg.text toUserWithJid:_jid];
NSMutableDictionary *dic_send = [[NSMutableDictionary alloc]init];
[dic_send setObject:txtmsg.text forKey:@"text"];
[data addObject:dic_send];
[tblobj reloadData];
txtmsg.text=@"";
 }
-(NSMutableArray *)getAllMessagesArrayWithOppositeUser:(XMPPJID *)xmppUser
{
XMPPMessageArchivingCoreDataStorage *storage = [XMPPMessageArchivingCoreDataStorage sharedInstance];
NSManagedObjectContext *moc = [storage mainThreadManagedObjectContext];
NSEntityDescription *entityDescription = [NSEntityDescription entityForName:@"XMPPMessageArchiving_Message_CoreDataObject"
                                                     inManagedObjectContext:moc];
NSFetchRequest *request = [[NSFetchRequest alloc]init];
[request setEntity:entityDescription];
NSError *error;
NSArray *messages = [moc executeFetchRequest:request error:&error];

data=[[NSMutableArray alloc] init];

@autoreleasepool {
    for (XMPPMessageArchiving_Message_CoreDataObject *message in messages) {

        if ([message.bareJid isEqual:xmppUser])
        {
            NSMutableDictionary *dict=[[NSMutableDictionary alloc] init];
            [dict setObject:message.body forKey:@"text"];
            [dict setObject:message.timestamp forKey:@"date"];
            if ([message isOutgoing]) {
                [dict setObject:@"1" forKey:@"type"];
                [dict setObject:[[message.bareJidStr componentsSeparatedByString:@"@"] firstObject] forKey:@"username"];
                [dict setObject:[UIColor greenColor] forKey:@"color"];
            }
            else{

                [dict setObject:@"2" forKey:@"type"];
                [dict setObject:[[message.bareJidStr componentsSeparatedByString:@"@"] firstObject] forKey:@"username"];
                //                    [dict setObject:userName forKey:@"username"];
                [dict setObject:[UIColor blueColor] forKey:@"color"];
             }
            [data addObject:dict];
          }
      }
  }

   return data;
}

我的错误在哪里?

编辑

 - (void)xmppStream:(XMPPStream *)sender didReceiveMessage:(XMPPMessage *)message
{

DDLogVerbose(@"%@: %@", THIS_FILE, THIS_METHOD);


if ([message isChatMessageWithBody])
{
    XMPPMessageArchivingCoreDataStorage *xmppMessageStorage = [XMPPMessageArchivingCoreDataStorage sharedInstance];
    XMPPMessageArchiving *xmppMessageArchiving = [[XMPPMessageArchiving alloc] initWithMessageArchivingStorage:xmppMessageStorage];

    [xmppMessageArchiving activate:xmppStream];
    [xmppMessageArchiving addDelegate:self delegateQueue:dispatch_get_main_queue()];
    XMPPUserCoreDataStorageObject *user = [xmppRosterStorage userForJID:[message from]
                                                             xmppStream:xmppStream
                                                   managedObjectContext:[self managedObjectContext_roster]];

    [[NSNotificationCenter defaultCenter] postNotificationName:MessageRecivedNotif object:message];

    NSString *body = [[message elementForName:@"body"] stringValue];
    NSString *displayName = [user displayName];

    if ([[UIApplication sharedApplication] applicationState] == UIApplicationStateActive)
    {
        UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:displayName
                                                            message:body
                                                           delegate:nil
                                                  cancelButtonTitle:@"Ok"
                                                  otherButtonTitles:nil];
        [alertView show];
    }
    else
    {
        // We are not active, so use a local notification instead
        UILocalNotification *localNotification = [[UILocalNotification alloc] init];
        localNotification.alertAction = @"Ok";
        localNotification.alertBody = [NSString stringWithFormat:@"From: %@\n\n%@",displayName,body];

        [[UIApplication sharedApplication] presentLocalNotificationNow:localNotification];
    }
  }

【问题讨论】:

  • 你找到任何解决方案然后告诉我我也在用 xmpp 制作聊天应用程序,现在正在研究如何在 tableview 中显示收到的消息...请帮助我
  • 是的,我已经完成了 anand acharya 的回答。
  • 好的,我会尝试..谢谢...您是否对 appdelegate 中的接收消息进行了任何更改
  • 不,我没有更改此方法中的任何内容。
  • 我没听懂...你能和我分享你的 .h 和 .m 文件吗

标签: ios xmpp


【解决方案1】:

你需要像这样在 uitableviewcellforrowatindexpath 方法中设置你的逻辑。

 - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
UITableViewCell *cell = [tblobj dequeueReusableCellWithIdentifier:@"cell"];
UILabel *lbl;
if (cell==nil)
{
    cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"cell"];

    if([[[data objectAtIndex:indexPath.row]valueForKey:@"type"] isEqualToString:@"2"])
    //if (chatLblRight == 1)
    {
        lbl = [[UILabel alloc]initWithFrame:CGRectMake(200, 10, 150, 44)];
        [lbl setTextColor:[UIColor redColor]];
        [cell.contentView   addSubview:lbl];
    }


}
if([[[data objectAtIndex:indexPath.row]valueForKey:@"type"] isEqualToString:@"2"])

//if([[[data objectAtIndex:indexPath.row]valueForKey:@"type"] isEqualToString:@"1"])
//if (chatLblRight == 1)
{
    lbl.text = [[data objectAtIndex:indexPath.row]valueForKey:@"text"];
    chatLblRight = 0;
    lbl = [[UILabel alloc]initWithFrame:CGRectMake(200, 10, 150, 44)];
    [lbl setTextColor:[UIColor redColor]];
    [cell.contentView   addSubview:lbl];

    return cell;
}
else
{
    cell.textLabel.text=[[data objectAtIndex:indexPath.row]valueForKey:@"text"];
    return cell;
  }

}

请检查此代码一次。

【讨论】:

    【解决方案2】:
    - (void)xmppStream:(XMPPStream *)sender didReceiveMessage:(XMPPMessage*)message
    {
    //in this the (XMPPMessage*)message parameter is xml data
    //parse you xml and create dictionary For eg : sampledict
    }
    

    通常当您从 XMPP 收到回复时,它就像 XML 数据一样。您必须解析并用于您的操作。

    在你的代码中

    if ([[UIApplication sharedApplication] applicationState] == UIApplicationStateActive)
    {
       // UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:displayName
                                                            message:body
                                                           delegate:nil
                                                  cancelButtonTitle:@"Ok"
                                                  otherButtonTitles:nil];
       // [alertView show];
    }
    else
    {
        // We are not active, so use a local notification instead
        UILocalNotification *localNotification = [[UILocalNotification alloc] init];
        localNotification.alertAction = @"Ok";
        localNotification.alertBody = [NSString stringWithFormat:@"From: %@\n\n%@",displayName,body];
    
        [[UIApplication sharedApplication] presentLocalNotificationNow:localNotification];
    }
    

    您使用过警报视图。因此,您必须隐藏警报视图,以免收到警报。而是管理您的观察者方法来获取数据并使用它

    -(void)messageReceived:(NSNotification*)notif
    { 
    XMPPMessage *message=(XMPPMessage*)notif.object;
    NSString *body = [[message elementForName:@"body"] stringValue];
    NSMutableDictionary *dic_recive = [[NSMutableDictionary alloc]init];
    [dic_recive setObject:body forKey:@"text"];
    [data addObject:dic_recive];
    chatLblRight = 1;
    [tblobj reloadData];
    }
    

    我想这会对你有所帮助..

    【讨论】:

    • 感谢重播。你应该投票寻求帮助。我必须在哪里写第一个代码?在应用程序 delegate.m 或我的 chatconversionview 控制器中?
    【解决方案3】:

    请到 xmpp 自定义类并发布这样的通知

    - (void)xmppStream:(XMPPStream *)sender didReceiveMessage:(XMPPMessage *)message
    {
    //parse you xml and create dictionary For eg : sampledict
    NSNotificationCenter *notificationCenter = [NSNotificationCenter defaultCenter];
                            [notificationCenter postNotificationName:@"updateValue" object:nil userInfo:sampledict];
    
    }
    

    并从您的班级收到通知,例如 使用通知之类的

    [[NSNotificationCenter defaultCenter] addObserver:self
                                                 selector:@selector(receiveUpdatedValues:)
                                                     name:@"updateValue"
                                                   object:nil];
    
    
    -(void)receiveUpdatedValues : (NSNotification *)notification
    {
    NSDictionary *dictinfo=notification.userInfo;
    // here use your info dict to get your message
    }
    

    【讨论】:

    • 感谢重播。什么是 sampledict,我必须在哪里声明它?目前我编辑了我的- (void)xmppStream:(XMPPStream *)sender didReceiveMessage:(XMPPMessage *)message 方法。 [租赁指导我。谢谢。
    猜你喜欢
    • 1970-01-01
    • 2013-06-28
    • 1970-01-01
    • 1970-01-01
    • 2016-06-01
    • 1970-01-01
    • 1970-01-01
    • 2013-06-21
    • 1970-01-01
    相关资源
    最近更新 更多