我从以下地址下载了此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);

    }

10-08 11:15