(六十八)使用XMPPFramework登录

按照XMPPFramework的官方样例,应该把登录代码放置在AppDelegate中,并且让注销成为私有方法。

XMPPFramework进行登录的步骤如下:

①连接主机,并且发送JID

②如果连接成功,则发送密码进行授权

③授权成功后,发送上线消息

④如果要注销,发送下线消息,并且断开连接。

一般让XMPPFramework工作在子线程中,和异步socket类似,通过代理来处理各个状态。

下面是使用框架登录的步骤:

①包含XMPPFramework.h

②定义XMPPStream成员属性,遵循XMPPStream代理协议:@interface AppDelegate () <XMPPStreamDelegate>{XMPPStream *_stream;}

③在application didFinishLaunch…方法中调用connectToHost方法连接主机:

注意其中XMPPStream的connectWithTimeout: error:方法返回false代表失败,应该打印错误信息。

这里使用的是本地openfire服务器,登录账户zs@soulghost.local,密码为123456。

如果XMPPStream为空,说明还没有创建,进行初始化:

– (void)setupXMPPStream{_stream = [[XMPPStream alloc] init];[_stream addDelegate:self delegateQueue:dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)];}连接主机的代码:

– (void)connectToHost{if (_stream == nil) {[self setupXMPPStream];}_stream.hostName = @"localhost";_stream.hostPort = 5222;// resource用于标识用户登陆的客户端类型XMPPJID *myJID = [XMPPJID jidWithUser:@"zs" domain:@"soulghost.local" resource:@"iPhone"];_stream.myJID = myJID;NSError *err = nil;if(![_stream connectWithTimeout:XMPPStreamTimeoutNone error:&err]){NSLog(@"%@",err);}}④连接主机成功和失败都有代理方法,如果成功应该发送密码:

– (void)xmppStreamDidConnect:(XMPPStream *)sender{NSLog(@"连接成功");[self sendPwdtoHost];}- (void)xmppStreamDidDisconnect:(XMPPStream *)sender withError:(NSError *)error{NSLog(@"连接断开,%@",error);}⑤如果连接成功,发送密码:

– (void)sendPwdtoHost{NSError *err = nil;[_stream authenticateWithPassword:@"123456" error:&err];if (err) {NSLog(@"%@",err);}}⑥授权成功和失败都有相应的方法:

– (void)xmppStreamDidAuthenticate:(XMPPStream *)sender{NSLog(@"授权成功");[self sendOnlineToHost];}- (void)xmppStream:(XMPPStream *)sender didNotAuthenticate:(DDXMLElement *)error{NSLog(@"授权失败,%@",error);}⑦如果授权成功,应该发送在线消息,在线是通过发送带有available标识的presence实现的:

– (void)sendOnlineToHost{XMPPPresence *presence = [XMPPPresence presenceWithType:@"available"];[_stream sendElement:presence];}⑧如果要离线,只需要发送带有unavailable标识的presence即可:

调用XMPPStream的disconnect方法可以断开与主机的连接。

– (void)logout{// 发送离线消息XMPPPresence *offline = [XMPPPresence presenceWithType:@"unavailable"];[_stream sendElement:offline];NSLog(@"注销成功");// 与服务器断开连接[_stream disconnect];}⑨如果要在其他地方调用logout,,只需要得到AppDelegate单例调用:

// 注销登录AppDelegate *app = [UIApplication sharedApplication].delegate;[app logout];

辽远或偏僻的地方,而会常常想起这一次的旅行,想起那座山,那个城,那些人……

(六十八)使用XMPPFramework登录

相关文章:

你感兴趣的文章:

标签云: