2015-06-15 3 views
1

Я работаю над проектом на основе XMPP. Я могу отправить сообщение, и оно отображается на экране беседы, но когда я получаю сообщение, оно отображается только в режиме предупреждения, которое невозможно увидеть на экране беседы.iOS 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]; 
[email protected]""; 
} 
-(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; 
} 

Где моя ошибка?

EDIT

- (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]; 
    } 
    } 
+0

У вас есть какое-либо решение, тогда скажите мне, что я также создаю приложение для чата с xmpp и теперь работаю над тем, как отображать полученное сообщение в tableview ... пожалуйста, помогите мне –

+0

да, я написал запись на ответ ананьи. –

+0

ok я попробую..отчеты ... у вас сделанные изменения в did получили сообщение в appdelegate –

ответ

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; 
    } 

} 

, пожалуйста, проверьте этот код один раз.

0

Пожалуйста, перейдите 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 
} 
+0

Спасибо за повтор. что такое sampledict и где я должен его объявить? в настоящее время я отредактировал мой метод '- (void) xmppStream: (XMPPStream *) отправителя didReceiveMessage: (XMPPMessage *). [аренда гид меня. Благодарю. –

1
- (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]; 
} 

Вы использовали alertview. Поэтому вам нужно скрыть свое предупреждение, чтобы вы не получали предупреждения. Вместо того, чтобы управлять метод наблюдателя, чтобы получить данные и использовать его

-(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]; 
} 

Я думаю, что это поможет ..

+1

спасибо за повтор. вы заслуживаете голосования за помощь. где я должен написать 1-й код? в приложении delegate.m или в моем контроллере chatconversionview? –

+0

получил ошибку, как недопустимое имя 'body' –

Смежные вопросы