[置顶] XMPPFrameWork IOS 开发(四)消息和好友上下线

来源:互联网 发布:如何下载spring源码 编辑:程序博客网 时间:2024/06/10 04:21

原始地址:XMPPFrameWork IOS 开发(四)

消息

[cpp] view plaincopyprint?
  1. //收到消息    
  2. - (void)xmppStream:(XMPPStream *)sender didReceiveMessage:(XMPPMessage *)message{    
  3.         
  4. //    NSLog(@"message = %@", message);    
  5.     //消息的内容   
  6.     NSString *msg = [[message elementForName:@"body"] stringValue];   
  7.     //消息发送者   
  8.     NSString *from = [[message attributeForName:@"from"] stringValue];    
  9.           
  10.     /****在此处****/  
  11.     //通知聊天页面有新消息,需要处理    
  12.         
  13. }   


发送消息

[cpp] view plaincopyprint?
  1. //发送消息的xml格式  
  2. <message from='发送者账号'  
  3.     to='接收者账号'  
  4.     type='chat'>  
  5.     <body>HELLO WORLD </body>  
  6.     </message>  


//代码组装

[cpp] view plaincopyprint?
  1. NSString *message = @"HELLO WORLD";  
  2.     NSXMLElement *body = [NSXMLElement elementWithName:@"body"];  
  3.     [body setStringValue:message];  
  4.       
  5.     //生成XML消息文档  
  6.     NSXMLElement *mes = [NSXMLElement elementWithName:@"message"];  
  7.     //消息类型  
  8.     [mes addAttributeWithName:@"type" stringValue:@"chat"];  
  9.     //发送给谁  
  10.     [mes addAttributeWithName:@"to" stringValue:@"接受者账号"];  
  11.     //由谁发送  
  12.     [mes addAttributeWithName:@"from" stringValue:@"发送者账号"];  
  13.     //组合  
  14.     [mes addChild:body];  
  15.       
  16.     //发送消息  
  17.     [[self xmppStream] sendElement:mes];  


好友上下线通知

[cpp] view plaincopyprint?
  1. - (void)xmppStream:(XMPPStream *)sender didReceivePresence:(XMPPPresence *)presence  
  2. {     
  3.     //取得好友状态  
  4.     NSString *presenceType = [presence type]; //online/offline  
  5.     //当前用户  
  6.     NSString *userId = [[sender myJID] user];  
  7.     //在线用户  
  8.     NSString *presenceFromUser = [[presence from] user];  
  9.     /* 
  10.      //如果不是自己,如果涉及多段登录,此处最好加上else,如果是自己离线的话,调用上线协议 
  11.      XMPPPresence *presence = [XMPPPresence presence]; 
  12.      [[self xmppStream] sendElement:presence]; 
  13.      */  
  14.     if (![presenceFromUser isEqualToString:userId])  
  15.     {  
  16.         //用户在线  
  17.         if ([presenceType isEqualToString:@"available"])  
  18.         {  
  19.             //列表和数据库都要相应改变  
  20.         }else if ([presenceType isEqualToString:@"unavailable"])//用户不在线  
  21.         {  
  22.             //列表和数据库都要相应改变  
  23.         }  
  24.     }  
  25. }  

0 0