Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to send and receive messages using XMPPFramework

I am creating a chat application using XMPP Framework in iPhone. I wish to know the process for sending and receiving messages. Can anyone give me a solution for this?

Thanks in advance.

like image 506
Lakshmi Avatar asked Dec 12 '22 15:12

Lakshmi


1 Answers

Download XMPPFramework and unzip it. There are several folders inside. Open the 'Xcode' folder > open 'iPhoneXMPP' folder > click on 'iPhoneXMPP.xcodeproj' > run it. It asks login credential first. Upon successful login, it will show your buddy list. It works fine for gmail. There is one call back method which is called for every incoming message:

- (void)xmppStream:(XMPPStream *)sender didReceiveMessage:(XMPPMessage *)message
{
    user = [xmppRosterStorage userForJID:[message from] xmppStream:sender     managedObjectContext:[self managedObjectContext_roster]];

    if ([message isChatMessageWithBody])
    {
        NSString *body = [[message elementForName:@"body"] stringValue];
    NSString *from = [[message attributeForName:@"from"] stringValue];
        NSMutableDictionary *m = [[NSMutableDictionary alloc] init];
        [m setObject:body forKey:@"msg"];
        [m setObject:from forKey:@"sender"];

        if ([[UIApplication sharedApplication] applicationState] == UIApplicationStateActive)
        {          
             NSLog(@"Applications are in active state");
             //send the above dictionary where ever you want
        }
        else
        {
            NSLog(@"Applications are in Inactive state");
            UILocalNotification *localNotification = [[UILocalNotification alloc] init];
            localNotification.alertAction = @"Ok";
            localNotification.applicationIconBadgeNumber=count;
            localNotification.alertBody =[NSString stringWithFormat:@"From:"%@\n\n%@",from,body];
            [[UIApplication sharedApplication] presentLocalNotificationNow:localNotification];
             //send the above dictionary where ever you want
        }
    }
}

For sending message we have to write our own method where ever you want:

-(void)sendMessage
{
    NSString *messageStr =messageField.text;

    if([messageStr length] > 0)
    {              
        NSLog(@"Message sending fron Gmail");
        NSXMLElement *body = [NSXMLElement elementWithName:@"body"];
        [body setStringValue:messageStr];
        NSXMLElement *message = [NSXMLElement elementWithName:@"message"];
        [message addAttributeWithName:@"type" stringValue:@"chat"];
        [message addAttributeWithName:@"to" stringValue:@"destination address"];
        [message addChild:body];
        NSLog(@"message1%@",message);

        [[self appDelegate].xmppSream sendElement:message];
    }    
}
like image 126
Venkat Avatar answered Dec 28 '22 11:12

Venkat