大学IT网 - 最懂大学生的IT学习网站! QQ资料交流群:367606806
当前位置:大学IT网 > IOS技巧 > XMPP收发消息2

XMPP收发消息2

关键词:收发消息XMPP  阅读(681) 赞(11)

[摘要]本文是对XMPP收发消息2的讲解,对学习IOS苹果软件开发有所帮助,与大家分享。

Message:

接着写

.h

 /*!
  *  @Author Dylan.
  *
  *  callback Block
  */
 typedef void(^sendSuccess)();
 typedef void(^sendFailure)(id);
 
 /*!
  *  sendMessageBy model
  */
 - (void)sendMessage: (ADMessageModel *)message
         sendSuccess: (sendSuccess)success
         sendFailure: (sendFailure)failure;
 
 /*!
  *  @Author Dylan.
  *
  *  unRead Msg
  */
 @property (nonatomic, strong) NSMutableDictionary * unReadMsg;
 
 /*!
  *  @Author Dylan.
  *
  *  new Msg
  */
 @property (nonatomic, copy) void (^newMessage) (id);
 
 
 @end

.m

 #pragma mark - initData
 - (void)initData {
     // 可做数据持久化
     self.unReadMsg = [NSMutableDictionary dictionary];
 }
 
 #pragma mark Methods
 - (void)sendMessage: (ADMessageModel *)message
         sendSuccess: (sendSuccess)success
         sendFailure: (sendFailure)failure {
     
     // set callback block
     self.success = success;
     self.failure = failure;
     
     NSXMLElement * body = [NSXMLElement elementWithName:@"body"];
     [body setStringValue:message.body];
     
     //生成XML消息文档
     NSXMLElement *mes = [NSXMLElement elementWithName:@"message"];
     //消息类型
     [mes addAttributeWithName:@"type" stringValue:@"chat"];
     //发送给谁
     [mes addAttributeWithName:@"to" stringValue:message.to];
     //由谁发送
     [mes addAttributeWithName:@"from" stringValue:message.from];
     //组合
     [mes addChild:body];
     //发送消息
     [[self xmppStream] sendElement:mes];
 }
 
 #pragma mark - delegeteMethods
 - (void)xmppStream:(XMPPStream *)sender didReceiveMessage:(XMPPMessage *)message {
     
     NSString * body = [[message elementForName:@"body"] stringValue];
     NSString * from = [[message attributeForName:@"from"] stringValue];
     
     if (body != nil) {
         
         NSMutableDictionary * msgDict = [NSMutableDictionary dictionary];
         ADMessageModel * model = [[ADMessageModel alloc] init];
         model.body = body;
         model.from = from;
         [msgDict setValue:model forKey:[ADCurrentTime getCurrentTime]];
         
         if ([from isEqualToString:[[NSUserDefaults standardUserDefaults] stringForKey:CURRENT_CHAT]]) {
             
             self.newMessage(msgDict);
         } else {
             // not current chat
             if ([_unReadMsg.allKeys containsObject:from]) {
                 [_unReadMsg[from] addObject:model];
             } else {
                 [_unReadMsg setValue:[NSMutableArray arrayWithObject:msgDict] forKey:from];
             }
         }
         
     }
 }
 
 @end


相关评论