【发布时间】:2011-07-05 13:19:57
【问题描述】:
我正在使用 iPhone 中的 XMPP 框架创建一个聊天应用程序。我想知道发送和接收消息的过程。谁能给我一个解决方案?
提前致谢。
【问题讨论】:
-
我确定 XMPP 框架有文档吗?
标签: ios objective-c xmpp xmppframework
我正在使用 iPhone 中的 XMPP 框架创建一个聊天应用程序。我想知道发送和接收消息的过程。谁能给我一个解决方案?
提前致谢。
【问题讨论】:
标签: ios objective-c xmpp xmppframework
快速 google 搜索显示许多 XMPP libraries,无论是 C/C++ 还是 ObjC。也许http://code.google.com/p/xmppframework/ 会是一个很好的起点,虽然我没有亲自尝试过。
【讨论】:
下载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];
}
}
【讨论】:
如果您从Room/Group 发送消息,请使用此代码发送消息。
[xmppRoom sendMessage:@"Hi All"];
不需要通过xmppStream 发送消息。这行代码非常适合我。
【讨论】:
@"Hi All" 作为 NSString 而不是 XMPPMessage 存在。与sendMessage 方法的输入不兼容。您将收到此错误:不兼容的指针类型将“NSString *”发送到“XMPPMessage *”类型的参数
XMPPRoom 类中使用- (void)sendMessage:(XMPPMessage *)message;。因此,您需要先初始化 XMPPMessage。
下面的组/房间发送消息是sn-p
XMPPMessage *message = [XMPPMessage message];
[message addBody:@"123"];
[self.currentRoom sendMessage:message1];
Where self.currentRoom is XMPPRoom
【讨论】:
这是在 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)
【讨论】: