iOS XMPP框架学习

先总结一下使用XMPP协议的流程

1.初始化XMPPStream,最好在程序启动(或者在某个单例类)代理方法中初始化,以保证只初始化一次,并方便随时访问。相关代码:

xmppStream = [[XMPPStream alloc] init];//实例化

[xmppStream addDelegate:self delegateQueue:dispatch_get_main_queue()];

[xmppStream setHostName:kXMPPHost];//设置主机名

[xmppStream setHostPort:5222];//设置端口

xmppStream.enableBackgroundingOnSocket = YES;//设备是否能在后台运行,不支持模拟器

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];

    }

}

6.接收上下线通知

- (void)xmppStream:(XMPPStream *)sender didReceivePresence:(XMPPPresence *)presence{}

7.接受好友请求

- (BOOL)xmppStream:(XMPPStream *)sender didReceiveIQ:(XMPPIQ *)iq











评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值