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

Registert New User to Openfire server using XMPP in iOS

我正在尝试在不使用入站注册的情况下将新用户注册到明火,还有一些其他设置是: bool allowSelfSignedCertificates = NO; bool allowSSLHostNameMismatch = NO;布尔 useSSL = 否。我在 Whosebug 上播下了一些示例,但其中 none 对我有好处,或者我没有掌握这个概念...

这是我的代码:

->.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

->.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

而且我想指出我的代码没有进入委托方法

更新:

Error Domain=XMPPStreamErrorDomain Code=1 "Attempting to connect while already connected or connecting." UserInfo=0x7fdc2af1f1c0 {NSLocalizedDescription=在已连接或正在连接时尝试连接。}

如果我评论这行:

[ xmppStream registerWithElements:elements error:nil];

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

@Laur Stefan

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

下载新演示

然后

在 - (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)connect 方法..

#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 连接到您的服务器后, 您可以通过以下方法获得响应。

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

//试试上面测试过的代码,如果有问题告诉我们..

所以,经过搜索,发现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);
}

//这个方法在Sing UP view controller中使用

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

}

要显示 online/offline 状态,我们必须实施 "NSFetchedResultsControllerDelegate"

@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;
}