先总结一下使用XMPP协议的流程
1.初始化XMPPStream,最好在程序启动(或者在某个单例类)代理方法中初始化,以保证只初始化一次,并方便随时访问。相关代码:
xmppStream = [[XMPPStream alloc] init];//实例化
[xmppStream addDelegate:self delegateQueue:dispatch_get_main_queue()];
[xmppStream setHostName:kXMPPHost];//设置主机名
[xmppStream setHostPort:5222];//设置端口
xmppReconnect = [[XMPPReconnect alloc] init];//初始化连接流 能在意外断开连接的情况下,自动重连。
xmppRosterStorage = [[XMPPRosterCoreDataStorage alloc] init];//花名册存储 XMPP使用coreData 本地化存储
xmppRoster = [[XMPPRoster alloc] initWithRosterStorage:xmppRosterStorage];//初始化花名册
xmppRoster.autoFetchRoster = YES;//是否自动获取花名册
xmppRoster.autoAcceptKnownPresenceSubscriptionRequests = YES;
//激活组件
[xmppReconnect activate:xmppStream];
[xmppRoster activate:xmppStream];
2.连接XMPP服务器 并设置JID。相关代码
[xmppStream setMyJID:[XMPPJID jidWithString:[NSString stringWithFormat:@"%@@%@",myJID,kXMPP_Domain]]];//设置JID,XMPPJID提供了一个不可变JID的实现,遵守NSCopying协议和NSCoding协议
NSError *error = nil;
if (![xmppStream connect:&error])
{
NSLog(error);
return NO;
}
return YES;
3.处理XMPP connect的代理方法
- (void)xmppStreamDidConnect:(XMPPStream *)sender{//连接成功后,授权认证
if (![xmppStream authenticateWithPassword:password error:&error])//授权
{
NSLog(@"Error authenticating: %@", error);
}
}
4.处理授权的代理方法
- (void)xmppStreamDidAuthenticate:(XMPPStream *)sender//授权成功
{
[self goOnline];//上线通知
[xmppRoster fetchRoster];//获取花名册
self.isLogined = YES;
}
- (void)xmppStream:(XMPPStream *)sender didNotAuthenticate:(NSXMLElement *)error//授权失败
{
NSLog(error);
}
- (void)goOnline//上线通知
{
XMPPPresence *presence = [XMPPPresence presence]; // type="available" is implicit
[xmppStream sendElement:presence];
}
- (void)goOffline//下线通知
{
XMPPPresence *presence = [XMPPPresence presenceWithType:@"unavailable"];
[xmppStream sendElement:presence];
}
5.接收消息
- (void)xmppStream:(XMPPStream *)sender didReceiveMessage:(XMPPMessage *)message{
if([[UIApplication sharedApplication] applicationState] != UIApplicationStateActive)//程序在后台 用本地提醒
{
UILocalNotification *localNotification = [[UILocalNotification alloc] init];
localNotification.alertAction = @"Ok";
localNotification.alertBody = [NSString stringWithFormat:@"From: %@\n\n%@",@"新消息:",@"123"];
[[UIApplication sharedApplication] presentLocalNotificationNow:localNotification];
}
}
- (void)xmppStream:(XMPPStream *)sender didReceivePresence:(XMPPPresence *)presence{}
7.接受好友请求
- (BOOL)xmppStream:(XMPPStream *)sender didReceiveIQ:(XMPPIQ *)iq