·您现在的位置: 云翼网络 >> 文章中心 >> 网站建设 >> app软件开发 >> IOS开发 >> XMPP收发消息2

XMPP收发消息2

作者:佚名      IOS开发编辑:admin      更新时间:2022-07-23

Message:

接着写

.h 

 1 /*!
 2  *  @Author Dylan.
 3  *
 4  *  callback Block
 5  */
 6 typedef void(^sendSuccess)();
 7 typedef void(^sendFailure)(id);
 8 
 9 /*!
10  *  sendMessageBy model
11  */
12 - (void)sendMessage: (ADMessageModel *)message
13         sendSuccess: (sendSuccess)success
14         sendFailure: (sendFailure)failure;
15 
16 /*!
17  *  @Author Dylan.
18  *
19  *  unRead Msg
20  */
21 @PRoperty (nonatomic, strong) NSMutableDictionary * unReadMsg;
22 
23 /*!
24  *  @Author Dylan.
25  *
26  *  new Msg
27  */
28 @property (nonatomic, copy) void (^newMessage) (id);
29 
30 
31 @end

.m

 1 #pragma mark - initData
 2 - (void)initData {
 3     // 可做数据持久化
 4     self.unReadMsg = [NSMutableDictionary dictionary];
 5 }
 6 
 7 #pragma mark Methods
 8 - (void)sendMessage: (ADMessageModel *)message
 9         sendSuccess: (sendSuccess)success
10         sendFailure: (sendFailure)failure {
11     
12     // set callback block
13     self.success = success;
14     self.failure = failure;
15     
16     NSxmlElement * body = [NSXMLElement elementWithName:@"body"];
17     [body setStringValue:message.body];
18     
19     //生成XML消息文档
20     NSXMLElement *mes = [NSXMLElement elementWithName:@"message"];
21     //消息类型
22     [mes addAttributeWithName:@"type" stringValue:@"chat"];
23     //发送给谁
24     [mes addAttributeWithName:@"to" stringValue:message.to];
25     //由谁发送
26     [mes addAttributeWithName:@"from" stringValue:message.from];
27     //组合
28     [mes addChild:body];
29     //发送消息
30     [[self xmppStream] sendElement:mes];
31 }
32 
33 #pragma mark - delegeteMethods
34 - (void)xmppStream:(XMPPStream *)sender didReceiveMessage:(XMPPMessage *)message {
35     
36     NSString * body = [[message elementForName:@"body"] stringValue];
37     NSString * from = [[message attributeForName:@"from"] stringValue];
38     
39     if (body != nil) {
40         
41         NSMutableDictionary * msgDict = [NSMutableDictionary dictionary];
42         ADMessageModel * model = [[ADMessageModel alloc] init];
43         model.body = body;
44         model.from = from;
45         [msgDict setValue:model forKey:[ADCurrentTime getCurrentTime]];
46         
47         if ([from isEqualToString:[[NSUserDefaults standardUserDefaults] stringForKey:CURRENT_CHAT]]) {
48             
49             self.newMessage(msgDict);
50         } else {
51             // not current chat
52             if ([_unReadMsg.allKeys containsObject:from]) {
53                 [_unReadMsg[from] addObject:model];
54             } else {
55                 [_unReadMsg setValue:[NSMutableArray arrayWithObject:msgDict] forKey:from];
56             }
57         }
58         
59     }
60 }
61 
62 @end