XMPP中常用对象们:
XMPPStream:xmpp基础服务类
XMPPRoster:好友列表类
XMPPRosterCoreDataStorage:好友列表(用户账号)在core data中的操作类
XMPPvCardCoreDataStorage:好友名片(昵称,签名,性别,年龄等信息)在core data中的操作类
XMPPvCardTemp:好友名片实体类,从数据库里取出来的都是它
xmppvCardAvatarModule:好友头像
XMPPReconnect:如果失去连接,自动重连
XMPPRoom:提供多用户聊天支持
XMPPPubSub:发布订阅
第一步 生成xmppstream对象 并且设置委托
- -(void)setupStream{
- //初始化XMPPStream
- xmppStream = [[XMPPStream alloc] init];
- [xmppStream addDelegate:self delegateQueue:dispatch_get_current_queue()];
- }
第二步 设置登陆帐户名字与服务器名字,并连接
- -(BOOL)connect{
- [self setupStream];
- //从本地取得用户名,密码和服务器地址
- NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
- NSString *userId = [defaults stringForKey:USERID];
- NSString *pass = [defaults stringForKey:PASS];
- NSString *server = [defaults stringForKey:SERVER];
- if (![xmppStream isDisconnected]) {
- return YES;
- }
- if (userId == nil || pass == nil) {
- return NO;
- }
- //设置用户
- [xmppStream setMyJID:[XMPPJID jidWithString:userId]];
- //设置服务器
- [xmppStream setHostName:server];
- //密码
- password = pass;
- //连接服务器
- NSError *error = nil;
- if (![xmppStream connect:&error]) {
- NSLog(@"cant connect %@", server);
- return NO;
- }
- return YES;
- }
连接服务器
- //启动连接操作后,回调函数(委托函数)
- - (void)xmppStreamWillConnect:(XMPPStream *)sender将被调用,表示将要连接
- - (void)xmppStreamDidConnect:(XMPPStream *)sender//登陆服务器成功
- {
- NSError *error = nil;
- //验证帐户密码
- NSString *password = @"test1";
- BOOL bRes = [_xmppStream authenticateWithPassword:password error:&error];
- }
- //验证成功的回调函数
- - (void)xmppStreamDidAuthenticate:(XMPPStream *)sender
- {
- XMPPPresence *presence = [XMPPPresencepresence];
- //可以加上上线状态,比如忙碌,在线等
- [[selfxmppStream] sendElement:presence];//发送上线通知
- }
- //验证失败的回调
- - (void)xmppStream:(XMPPStream *)sender didNotAuthenticate:(NSXMLElement *)error