1. 程式人生 > >iOS XMPP群聊方法的實現

iOS XMPP群聊方法的實現

首先需要建立一個房間:

xmppRoom = [[XMPPRoom alloc] initWithRoomStorage:self jid:[XMPPJID jidWithString:[NSString stringWithFormat:@"%@@%@", jidString, @"conference.192.168.1.117"]]];
    [xmppRoom activate:xmppStream];
    [xmppRoom addDelegate:self delegateQueue:dispatch_get_main_queue()];

加入房間:

[[self xmppRoom] joinRoomUsingNickname:[[[NSUserDefaults standardUserDefaults] objectForKey:@"UserInfo"] valueForKey:@"userId"] history:nil];

此時房間ID就出現在好友列表內,可以正常進入聊天。

其次邀請好友:

[[self xmppRoom] inviteUser:[XMPPJID jidWithString:[NSString stringWithFormat:@"%@@192.168.1.117", friendIDFeild.text]] withMessage:@"join room!"];

客戶端要對收到邀請做出響應,方法如下:

新建一個XMPPMUC:

xmppMUC = [[XMPPMUC alloc] initWithDispatchQueue:dispatch_get_main_queue()];
    [xmppMUC activate:xmppStream];
    [xmppMUC addDelegate:self delegateQueue:dispatch_get_main_queue()];
類要實現XMPPMUCDelegate
-(void)xmppMUC:(XMPPMUC *)sender roomJID:(XMPPJID *)roomJID didReceiveInvitation:(XMPPMessage *)message
{
    NSLog(@"%@", message);
    xmppRoom = [[XMPPRoom alloc] initWithRoomStorage:self jid:roomJID];
    [xmppRoom activate:xmppStream];
    [xmppRoom addDelegate:self delegateQueue:dispatch_get_main_queue()];
    [xmppRoom joinRoomUsingNickname:[[[NSUserDefaults standardUserDefaults] objectForKey:@"UserInfo"] valueForKey:@"userId"] history:nil];
}
其中
[xmppRoom joinRoomUsingNickname:[[[NSUserDefaults standardUserDefaults] objectForKey:@"UserInfo"] valueForKey:@"userId"] history:nil];

為確認加入房間。

當你接受請求後,房間id會出現在聯絡人列表中,正常聊天就可以了,聊天資訊的type為groupchat,這部分在XMPP基礎中有,不做贅述。此為初步,後續補充。