1.带内注册(In-band registration)的概念
带内注册指的是未在你的服务器上开通账号的用户可以通过xmpp协议注册新账号。相反的概念是带外注册(out-of-band registration),例如 你必须到某个指定的web页面进行注册。
如果服务器允许带内注册,那么我们就可以通过自己开发的客户端注册新账号。与带内注册相关的协议是XEP-0077。
2.使用XMPPFramework进行带内注册
XMPPStream.h中声明了进行简单带内注册(提供用户名和密码进行注册)的函数
- (BOOL)registerWithPassword:(NSString *)password error:(NSError **)errPtr;
注册前需要先建立stream连接, 因为没有帐号,所以需要建立匿名连接
NSError *err;
NSString *tjid = [[NSString alloc] initWithFormat:@"anonymous@%@", server.text];
[[delegate xmppStream] setMyJID:[XMPPJID jidWithString:tjid]];
if ( ![[delegate xmppStream] connect:&err])
{
UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"连接服务器失败"
message:[err localizedDescription]
delegate:nil
cancelButtonTitle:@"Ok"
otherButtonTitles:nil];
[alertView show];
}
建立连接之后, 不需要进行用户验证, 可以如下处理 – 如果是在注册,则跳过验证这一步
- (void)xmppStreamDidConnect:(XMPPStream *)sender
{
DDLogVerbose(@"%@: %@", THIS_FILE, THIS_METHOD);
isXmppConnected = YES;
NSError *error = nil;
if (isRegister == YES)
return;
if (![[self xmppStream] authenticateWithPassword:password error:&error])
{
DDLogError(@"Error authenticating: %@", error);
}
}
xmppStream connect 是立即返回的, 所以connect返回并不能说明连接已经建立好. [delegate xmppStream] isConnected 为YES时才能确定连接已经建立好.
连接建立好之后,我们就可以发注册信息
NSString *jid = [[NSString alloc] initWithFormat:@"%@@%@", user.text, server.text];
[[delegate xmppStream] setMyJID:[XMPPJID jidWithString:jid]];
NSError *error=nil;
if (![[delegate xmppStream] registerWithPassword:password.text error:&error])
{
UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"创建帐号失败"
message:[error localizedDescription]
delegate:nil
cancelButtonTitle:@"Ok"
otherButtonTitles:nil];
[alertView show];
}
registerWithPassword:error 方法也是立即返回的
需要通过代理方法来判断注册是否成功
注册成功会调用:- (void)xmppStreamDidRegister:(XMPPStream *)sender
注册失败会调用:- (void)xmppStream:(XMPPStream *)sender didNotRegister:(NSXMLElement *)error
- (void)xmppStreamDidRegister:(XMPPStream *)sender
{
DDLogVerbose(@"%@: %@", THIS_FILE, THIS_METHOD);
registerSuccess = YES;
UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"创建帐号成功"
message:@""
delegate:self
cancelButtonTitle:@"Ok"
otherButtonTitles:nil];
[alertView show];
}
- (void)xmppStream:(XMPPStream *)sender didNotRegister:(NSXMLElement *)error
{
DDLogVerbose(@"%@: %@", THIS_FILE, THIS_METHOD);
UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"创建帐号失败"
message:@"用户名冲突"
delegate:nil
cancelButtonTitle:@"Ok"
otherButtonTitles:nil];
[alertView show];
}