我从以下地址下载了此iOS客户端:https://github.com/robbiehanson/XMPPFramework/,并想要添加一些代码以便它可以发送消息。
我创建了一个名为ChatViewController
的新类,并从RootViewController
加载了它。初始化此视图控制器时,我将xmppstream
作为以下参数传递:
stream =[[self appDelegate]xmppStream];
ChatViewController *chat = [[ChatViewController alloc]initWithStream:stream jid:user.jid];
[self.navigationController pushViewController:chat animated:YES];
我在
initWithStream
中签入了可以使用从RootViewController
获得的流发送消息的功能,但是我无法通过单击ChatViewController
上的按钮来发送消息。ChatViewController
的m文件如下:#import "ChatViewController.h"
#import "XMPPFramework.h"
@interface ChatViewController ()
@end
@implementation ChatViewController
@synthesize MyxmppStream;
@synthesize jid;
-(id)initWithStream:(XMPPStream *)stream jid:(XMPPJID *)ajid{
self = [super initWithNibName:@"ChatViewController" bundle:nil];
if (self) {
jid = ajid;
MyxmppStream = stream;
}
return self;
}
- (IBAction)SendMessage:(id)sender {
NSXMLElement *body = [NSXMLElement elementWithName:@"body"];
[body setStringValue:@"aaaa"];
NSXMLElement *message = [NSXMLElement elementWithName:@"message"];
[message addAttributeWithName:@"type" stringValue:@"chat"];
[message addAttributeWithName:@"to" stringValue:[jid full]];
[message addChild:body];
[MyxmppStream sendElement:message];
}
@end
如果将代码发送消息放在
initWithStream
中,它可以正常工作并成功发送消息,但是SendMessage
中的相同代码根本不起作用。 最佳答案
尝试这个希望能起作用的方法:
- (IBAction)sendMessage {
sender = [[[[self appDelegate] xmppStream] myJID] bare];
NSString *messageStr = self.messageField.text;
NSLog(@"The Mesage%@",messageStr);
if([messageStr length] > 0) {
NSXMLElement *body = [NSXMLElement elementWithName:@"body"];
[body setStringValue:messageStr];
XMPPMessage *message = [XMPPMessage elementWithName:@"message"];
[message addAttributeWithName:@"type" stringValue:@"chat"];
[message addAttributeWithName:@"to" stringValue:chatWithUser];
[message addChild:body];
self.messageField.text = messageStr;
NSMutableDictionary *m = [[NSMutableDictionary alloc] init];
[m setObject:[messageStr substituteEmoticons] forKey:@"msg"];
[m setObject:sender forKey:@"sender"];
[messages addObject:m];
[[self xmppStream ] sendElement:message];
NSLog(@"message :",messages);
}