我正在使用iPhone的XMPP框架创建聊天应用程序。我想了解发送和接收消息的过程。有人可以给我一个解决方案吗?
提前感谢。
提前感谢。
下载XMPPFramework并解压缩。里面有几个文件夹。打开“Xcode”文件夹 > 打开“iPhoneXMPP”文件夹 > 点击“iPhoneXMPP.xcodeproj” > 运行它。首先输入登录凭据。成功登录后,它将显示您的好友列表。它适用于 Gmail,并且每收到一条消息都会调用一个回调方法:
- (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
}
}
}
我们需要编写自己的方法来发送消息,放在任何您想要的位置:
-(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];
}
}
XMPPMessage *message = [XMPPMessage message];
[message addBody:@"123"];
[self.currentRoom sendMessage:message1];
Where self.currentRoom is XMPPRoom
房间/群组
发送消息,则使用此代码发送消息。[xmppRoom sendMessage:@"Hi All"];
xmppStream
发送消息。这一行代码对我来说完美地工作。NSString
而非 XMPPMessage
。无法作为 sendMessage
方法的输入参数。您将会收到以下错误提示:Incompatible pointer types sending 'NSString *' to parameter of type 'XMPPMessage *'。 - Keith OYSXMPPRoom
类中使用了- (void)sendMessage:(XMPPMessage *)message;
。因此,你需要先初始化一个XMPPMessage
。 - Keith OYS这里提供了一种使用Swift 3中的XMPPFramework发送消息的解决方案。
let user = XMPPJID(string: "user@jabjab.de")
let msg = XMPPMessage(type: "chat", to: user)
msg?.addBody("Message to send")
self.xmppStream.send(msg)
快速的谷歌搜索可以发现许多XMPP库,包括C/C++或ObjC。也许http://code.google.com/p/xmppframework/是一个不错的起点,虽然我个人没有尝试过。