在iOS中使用XMPP向Openfire服务器注册新用户

时间:2015-02-24 10:02:27

标签: ios xmpp openfire

我正在尝试将新用户注册到开放式火灾而不使用入站注册,还有一些其他设置: bool allowSelfSignedCertificates = NO; bool allowSSLHostNameMismatch = NO; bool useSSL = NO。我在stackoverflow上播下了一些例子,但没有一个对我有好处,或者我没有掌握这个概念......

这是我的代码:

- > .h文件:

#import <UIKit/UIKit.h>
#import <CoreData/CoreData.h>
#import "XMPP.h"
#import "XMPPRoster.h"

@interface SignUpViewController : UIViewController <UITextFieldDelegate, UIApplicationDelegate, XMPPRosterDelegate, XMPPStreamDelegate>
{
    XMPPStream *xmppStream;
}
@property (nonatomic, strong, readonly) XMPPStream *xmppStream;

@end

- &GT; .m文件

- (void)signUpButtonFunction{
    NSLog(@"SignUp function");

    [[self xmppStream] setHostName:@"IP_ADDRESS"];
    [[self xmppStream] setHostPort:5222];
    XMPPJID *jid=[XMPPJID jidWithString:emailTextField.text];
    [[self xmppStream] setMyJID:jid];
    [[self xmppStream] connectWithTimeout:3.0 error:nil];

    NSMutableArray *elements = [NSMutableArray array];
    [elements addObject:[NSXMLElement elementWithName:@"username" stringValue:@"venkat"]];
    [elements addObject:[NSXMLElement elementWithName:@"password" stringValue:@"dfds"]];
    [elements addObject:[NSXMLElement elementWithName:@"name" stringValue:@"eref defg"]];
    [elements addObject:[NSXMLElement elementWithName:@"email" stringValue:@"abc@bbc.com"]];

    [ xmppStream registerWithElements:elements error:nil];

}


//server connect delegate methods are not working at least it doesn't enter in them
- (void)xmppStreamDidRegister:(XMPPStream *)sender{


    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Registration" message:@"Registration Successful!" delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil, nil];
    [alert show];
}


- (void)xmppStream:(XMPPStream *)sender didNotRegister:(NSXMLElement *)error{

    DDXMLElement *errorXML = [error elementForName:@"error"];
    NSString *errorCode  = [[errorXML attributeForName:@"code"] stringValue];

    NSString *regError = [NSString stringWithFormat:@"ERROR :- %@",error.description];

    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Registration Failed!" message:regError delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil, nil];

    if([errorCode isEqualToString:@"409"]){

        [alert setMessage:@"Username Already Exists!"];
    }   
    [alert show];
}

这些是我正在使用的库: git library

我还要指出我的代码没有输入委托方法

更新:

  • 将signUpButtonFunction更改为:

    xmppStream = [[XMPPStream alloc] init];
    [xmppStream addDelegate:self delegateQueue:dispatch_get_main_queue()];
    [[self xmppStream] setHostName:@"IP_ADDRESS"];
    [[self xmppStream] setHostPort:5222];
    [[self xmppStream] setMyJID:[XMPPJID jidWithString:@"abc@newrosoft.com"]];
    [[self xmppStream] connectWithTimeout:XMPPStreamTimeoutNone error:nil];
    
    NSMutableArray *elements = [NSMutableArray array];
    [elements addObject:[NSXMLElement elementWithName:@"username" stringValue:@"username"]];
    [elements addObject:[NSXMLElement elementWithName:@"password" stringValue:@"password"]];
    [elements addObject:[NSXMLElement elementWithName:@"name" stringValue:@"eref defg"]];
    [elements addObject:[NSXMLElement elementWithName:@"email" stringValue:@"abc@newrosoft.com"]];
    
    [ xmppStream registerWithElements:elements error:nil];
    
    NSError *error = nil;
    if (![xmppStream connectWithTimeout:XMPPStreamTimeoutNone error:&error])
    {
        UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"Error connecting"
                                                        message:@"See console for error details."
                                                       delegate:nil
                                              cancelButtonTitle:@"Ok"
                                              otherButtonTitles:nil];
        [alertView show];
        NSLog(@"%@",error);
    
  • 我收到错误:

错误域= XMPPStreamErrorDomain代码= 1“在已连接或连接时尝试连接。” UserInfo = 0x7fdc2af1f1c0 {NSLocalizedDescription =在连接或连接时尝试连接。}

如果我评论该行:

[ xmppStream registerWithElements:elements error:nil];

然后错误消失,但它仍然没有进入委托方法。

3 个答案:

答案 0 :(得分:1)

所以,经过搜索后我发现openFire上可以安装一个允许正常注册的插件,所以我已经实现了下一个注册方法:

NSString *urlToCall = @"http://MyIP:9090/plugins/userService/userservice?type=add&secret=BigSecretKey&username=testUser&password=testPass&name=testName&email=test@gmail.com";
NSURL *url = [NSURL URLWithString:urlToCall];
NSMutableURLRequest *theRequest = [NSMutableURLRequest requestWithURL:url];
[theRequest setHTTPMethod:@"GET"];
NSError *error = nil;
NSURLResponse *response;
NSData *result = [NSURLConnection sendSynchronousRequest:theRequest returningResponse:&response error:&error];
NSString *responseString = [[NSString alloc] initWithData:result encoding:NSUTF8StringEncoding];
if ([responseString  isEqual: @"<result>ok</result>\r\n"]) {
    NSLog(@"user created");

} else {
   NSLog( @"user NOT created");
    NSLog(@"%@",responseString);
}

答案 1 :(得分:0)

@Laur Stefan

首先从https://github.com/robbiehanson/XMPPFramework

下载新演示

然后

in - (void)goOnline Change

 #warning Set here Server Name...
        if([domain isEqualToString:@"rakeshs-mac-mini.local"])
        {
            NSXMLElement *priority = [NSXMLElement elementWithName:@"priority" stringValue:@"24"];
            [presence addChild:priority];
        }

然后

in - (BOOL)连接方法..

#warning Set Username as username@servername
    myJID = [NSString stringWithFormat:@"%@@rakeshs-Mac-mini.local",myJID];

    [xmppStream setMyJID:[XMPPJID jidWithString:myJID]];
    password = myPassword;

    NSLog(@"username: %@,Password : %@",myJID,myPassword);

从OpenFire连接到YOur服务器后, 你可以从下面的方法得到回应。

- (void)xmppStream:(XMPPStream *)sender didReceiveMessage:(XMPPMessage *)message

//尝试以上测试过的代码,如果有任何问题告诉我们..

答案 2 :(得分:0)

//此方法用于Sing UP视图控制器

-(BOOL)createNewAccountForXmppWithUserName:(NSString*)userNameJID  andPassword:(NSString*)userPassword{
    if (userNameJID == nil || userPassword == nil) {
        return NO;
    }
    NSString *domain = @"abc.com";
    self.xmppStream.hostName = domain;
    int port = 5222;
    self.xmppStream.hostPort = port;
    useSSL               = NO;
    customCertEvaluation = NO;
    NSString * userName = [NSString stringWithFormat:@"%@@abc.com",userNameJID];
    XMPPJID *jid = [XMPPJID jidWithString:userName resource:nil];
    self.xmppStream.myJID = jid;
    NSError *error = nil;
    BOOL success;
    success = [[self xmppStream] registerWithPassword:password error:&error];
    if(![[self xmppStream] isConnected])
    {
        if (useSSL)
            success = [[self xmppStream] oldSchoolSecureConnectWithTimeout:XMPPStreamTimeoutNone error:&error];
        else
            success = [[self xmppStream] connectWithTimeout:XMPPStreamTimeoutNone error:&error];
        password = userPassword;
        success = [[self xmppStream] registerWithPassword:password error:&error];
    }
    else
    {
        password = userPassword;   
        success = [[self xmppStream] registerWithPassword:password error:&error];
    }
    if (success)
    {
        isRegistering = YES;
        NSLog(@"Successfully Register on XMPP Server");
    }    
    return YES;

}

要显示在线/离线状态,我们必须实施&#34; NSFetchedResultsControllerDelegate&#34;

@interface AKSMessageViewController : UIViewController<UITableViewDataSource,UITableViewDelegate, NSFetchedResultsControllerDelegate>
{
    NSFetchedResultsController *fetchedResultsController;
}

并实施

- (void)controllerDidChangeContent:(NSFetchedResultsController *)controller
{
    //remove previous data or clear array

    [[self xmppUserArray] removeAllObjects];
    [[[AKSGetCareerGlobalClass SharedInstance] onlineUserArray] removeAllObjects];


    //get data from core data
    self.xmppUserArray=[[[self fetchedResultsController] fetchedObjects] mutableCopy];


    for (int i=0; i<[[self xmppUserArray] count]; i++) {

        if ([[[[self xmppUserArray] objectAtIndex:i] valueForKey:@"sectionNum"] integerValue]==0) {
            //this is user is online
            [[[AKSGetCareerGlobalClass SharedInstance] onlineUserArray] addObject:[[[self xmppUserArray] objectAtIndex:i] valueForKey:@"nickname"]];

        }
    }


    [[self msgTableView] reloadData];

}

//和

#pragma mark NSFetchedResultsController
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

- (NSFetchedResultsController *)fetchedResultsController
{
    if (fetchedResultsController == nil)
    {
        NSManagedObjectContext *moc = [[self appDelegate] managedObjectContext_roster];

        NSEntityDescription *entity = [NSEntityDescription entityForName:@"XMPPUserCoreDataStorageObject"
                                                  inManagedObjectContext:moc];

        NSSortDescriptor *sd1 = [[NSSortDescriptor alloc] initWithKey:@"sectionNum" ascending:YES];
        NSSortDescriptor *sd2 = [[NSSortDescriptor alloc] initWithKey:@"displayName" ascending:YES];

        NSArray *sortDescriptors = [NSArray arrayWithObjects:sd1, sd2, nil];
        //NSSortDescriptor *sd2 = [[NSSortDescriptor alloc] initWithKey:@"displayName" ascending:YES];

        //NSString *myJID = [[NSUserDefaults standardUserDefaults] stringForKey:@"userJID"];
        //NSLog(@"My JID ====>%@",myJID);

        NSPredicate *predicate = [NSPredicate predicateWithFormat:@"subscription=='both'"];


        NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
        [fetchRequest setEntity:entity];
        [fetchRequest setPredicate:predicate];
        [fetchRequest setSortDescriptors:sortDescriptors];
        [fetchRequest setFetchBatchSize:20];

        fetchedResultsController = [[NSFetchedResultsController alloc] initWithFetchRequest:fetchRequest
                                                                       managedObjectContext:moc
                                                                         sectionNameKeyPath:@"sectionNum"
                                                                                  cacheName:nil];
        [fetchedResultsController setDelegate:self];


        NSError *error = nil;
        if (![fetchedResultsController performFetch:&error])
        {
            DDLogError(@"Error performing fetch: %@", error);
        }

    }

    return fetchedResultsController;
}