2012-04-21 13 views
12

He desarrollado el cliente de XMPP Chat para iOS y ahora estoy investigando cómo hacer un nuevo registro de usuario desde iOS. ¿Alguien puede ayudar con los métodos utilizados para registrar un nuevo usuario? Como necesita comunicarse con el Servidor y almacenar el nombre de usuario y la contraseña en la base de datos del servidor. Por favor ayuda, lo estoy buscando desde 2 días.Métodos para el registro de nuevos usuarios xmpp framework iOS

+0

Mencionar el servidor utiliza haría una gran diferencia. – ggozad

+0

Estoy usando el servidor OpenFire, aunque investigué sobre esto y el método utilizado para el registro en la biblioteca de framework xmpp es - (BOOL) supportsInBandRegistration; - (BOOL) registerWithPassword: (NSString *) error de contraseña: (NSError **) errPtr; Pero buscando cómo implementarlo. – obaid

+1

Eche un vistazo a mi respuesta aquí: http://stackoverflow.com/questions/9988206/new-registration-on-openfire-with-strophe-js/10000927#10000927 – ggozad

Respuesta

9

Esta solución ha funcionado para mí

NSString *username = @"[email protected]_SERVER_IP_HERE"; // OR [NSString stringWithFormat:@"%@@%@",username,XMPP_BASE_URL]] 
NSString *password = @"SOME_PASSWORD"; 

AppDelegate *del = (AppDelegate *)[[UIApplication sharedApplication] delegate]; 

del.xmppStream.myJID = [XMPPJID jidWithString:username]; 

NSLog(@"Does supports registration %ub ",); 
NSLog(@"Attempting registration for username %@",del.xmppStream.myJID.bare); 

if (del.xmppStream.supportsInBandRegistration) { 
    NSError *error = nil; 
    if (![del.xmppStream registerWithPassword:password error:&error]) 
    { 
     NSLog(@"Oops, I forgot something: %@", error); 
    }else{ 
     NSLog(@"No Error"); 
    } 
} 

// You will get delegate called after registrations in either success or failure case. These delegates are in XMPPStream class 
// - (void)xmppStreamDidRegister:(XMPPStream *)sender 
//- (void)xmppStream:(XMPPStream *)sender didNotRegister:(NSXMLElement *)error 
+0

Oye, probé tu código pero no funcionó para mí. No puedo conectar XMPP a Openfire. Por favor, ayúdame a saber cómo hacer que esto suceda. Estoy buscando la respuesta por 1 semana pero no recibí ninguna ayuda. Por favor, hágame saber cómo configurar XMPP. @rohit mandiwal. –

+0

¿Hay alguna manera de hacerlo si todavía no tiene una cuenta en el servidor? – sudo

+0

no funciona ..... –

10
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:@"accountType" stringValue:@"3"]]; 
[elements addObject:[NSXMLElement elementWithName:@"deviceToken" stringValue:@"adfg3455bhjdfsdfhhaqjdsjd635n"]]; 

[elements addObject:[NSXMLElement elementWithName:@"email" stringValue:@"[email protected]"]]; 

[[[self appDelegate] xmppStream] registerWithElements:elements error:nil]; 

Sabremos si el registro se ha realizado correctamente o no a través de los delegados que figuran a continuación.

- (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]; 
} 
+0

¿Hola Karun donde estableces el nombre de host y el nombre de puerto? –

+0

hi brother, - (void) xmppStreamDidRegister: (XMPPStream *) el método del remitente no está llamando. cómo debo verificar si el usuario está registrado o no –

+0

no funciona ... –

0

Nueva usuario puede registrarse en el servidor XMPP de iOS por dos métodos como

Methode 1.) Por En la banda de Registro (In- el registro de banda significa que los usuarios que no tienen una cuenta en su servidor pueden registrar uno usando el protocolo XMPP, por lo que el registro permanece "en banda", dentro del mismo protocolo que ya está usando). Debe usar XEP -0077 extensión.

Y su servidor también debe admitir In Band Registration.

Utilice estos pasos para la banda de Registro En

paso 1: conectar con xmppStream

- (BOOL)connectAndRegister 
{ 
    if (![xmppStream isDisconnected]) { 
     return YES; 
    } 

    NSString *myJID = @"[email protected]_SERVER_IP_HERE"; // OR [NSString stringWithFormat:@"%@@%@",username,XMPP_BASE_URL]] 
    NSString *myPassword = @"SOME_PASSWORD"; 

    // 
    // If you don't want to use the Settings view to set the JID, 
    // uncomment the section below to hard code a JID and password. 
    // 
    // Replace me with the proper JID and password: 
    // myJID = @"[email protected]/xmppframework"; 
    // myPassword = @""; 

    if (myJID == nil || myPassword == nil) { 
     DDLogWarn(@"JID and password must be set before connecting!"); 

     return NO; 
    } 

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

    NSError *error = nil; 
    if (![xmppStream connect:&error]) 
    { 
     UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"Error connecting" 
                  message:@"See console for error details." 
                  delegate:nil 
                cancelButtonTitle:@"Ok" 
                otherButtonTitles:nil]; 
     [alertView show]; 

     DDLogError(@"Error connecting: %@", error); 

     return NO; 
    } 

    return YES; 
} 

NSString *password declaran en parte de su archivo @interface

paso 2: Cuando xmppStream Delegar - (void)xmppStreamDidConnect:(XMPPStream *)sender llamar

paso 3: Iniciar registro en banda a través de Inscripción como

- (void)xmppStreamDidConnect:(XMPPStream *)sender{ 
    DDLogVerbose(@"%@: %@", THIS_FILE, THIS_METHOD); 
    [[NSNotificationCenter defaultCenter] postNotificationName:XMPPStreamStatusDidConnectNotification 
                 object:nil 
                 userInfo:nil]; 
    _isXmppConnected = YES; 
    NSError *error = nil; 
    DDLogVerbose(@"Start register via In-Band Registration..."); 

    if (xmppStream.supportsInBandRegistration) { 

     if (![xmppStream registerWithPassword:password error:&error]) { 
      NSLog(@"Oops, I forgot something: %@", error); 
     }else { 
      NSLog(@"No Error"); 
    } 
    } 
// [_xmppStream authenticateWithPassword:password error:&error]; 
} 

paso 4: Comprobar el registro éxito o el fracaso de XMPPStream delegado

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

Methode 2.) Por XMPP Rest Api en el servidor openFire instaló un complemento (complemento Rest Api) que permite el registro normal.

utilizar estos pasos para Resto Api de Registro

paso 1: Instalar Plugin API REST en el servidor

paso 2: Configurar el servidor de API REST como servidor -> Configuración del servidor -> Resto Api luego habilítalos.

Puede usar la "Autorización de clave secreta" para el registro de usuario seguro, así que cópielo del servidor de Openfire y úselo cuando se solicita el registro de la API de reposo.

paso 3: llamada API REST para el registro

-(void)CreateUserAPI 
{ 
    NSDictionary *dict = [NSDictionary dictionaryWithObjectsAndKeys:@"abc",@"username",@"SOME_PASSWORD",@"password",@"abc-nickname",@"name",@"[email protected]",@"email", nil]; 
    NSData* RequestData = [NSJSONSerialization dataWithJSONObject:dict options:0 error:nil]; 

    NSMutableURLRequest *request = [ [ NSMutableURLRequest alloc ] initWithURL: [ NSURL URLWithString:[NSString stringWithFormat:@"%@users",RESTAPISERVER]]]; 


    [request setHTTPMethod: @"POST"]; 
    [request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"]; 
    [request setValue:AuthenticationToken forHTTPHeaderField:@"Authorization"]; 
    [request setHTTPBody: RequestData]; 

    NSURLSession *session = [NSURLSession sharedSession]; 
    [[session dataTaskWithRequest:request 
      completionHandler:^(NSData *data, 
           NSURLResponse *response, 
           NSError *error) { 
       // handle response 
       if (!error) 
       { 

        NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *) response; 
        if ([httpResponse statusCode]==201) 
        { 

         NSLog(@"Registration Successful"); 

        }else 
        { 
         NSLog(@"Registration failed"); 
        } 

       }else 
       { 
        NSLog(@"Try again for registration"); 
       } 


      }] resume]; 
} 

RESTAPISERVER es una cadena API REST URL.

AuthenticationToken es un "Autenticación de clave secreta" (mensaje del servidor Openfire)

Cuestiones relacionadas