我从Xamarin的示例应用Chat借用了聊天应用的概念。此示例具有预先填充的消息列表,然后显示在聊天窗口中。我使用相同的方法,但添加了推送通知,以实现不同用户之间的聊天。当用户收到消息时,会在AppDelegate
文件中收到通知。
然后我有一个MessageBus,它发布新的传入消息。尽管已订阅,但新的传入消息永远不会显示在聊天窗口中。
问题
以下是我的代码:
AppDelegate.cs
public override bool FinishedLaunching (UIApplication application, NSDictionary launchOptions)
{
// Handle Push Notifications
ParsePush.ParsePushNotificationReceived += (object sender, ParsePushNotificationEventArgs args) => {
// Process Push Notification payload here.
object value;
args.Payload.TryGetValue("alert", out value);
nint badgeNumber = UIApplication.SharedApplication.ApplicationIconBadgeNumber;
badgeNumber++;
UIApplication.SharedApplication.ApplicationIconBadgeNumber = badgeNumber;
char[] delimiters = {':'};
string[] words = value.ToString().Split(delimiters);
object[] data = new object[2];
data[0] = words[0];
data[1] = words[1];
//dataManager.getMessageBus().Post("message", this, data);
//Post the messages
mBus = dataManager.getMessageBus();
publishMessage(words);
};
}
void publishMessage(string[]message)
{
try{
object[] data = new object[2];
data[0] = message[0];
data[1] = message[1];
var messageEvent = new CoreMessageBusEvent ("message") {
Sender = this,
Data = data
};
mBus.Post (messageEvent);
}catch(Exception ex)
{
Console.WriteLine (ex.Message + ex.StackTrace);
}
}
的ViewController
public partial class ViewController : UIViewController
{
public override void ViewDidLoad ()
{
base.ViewDidLoad ();
try
{
SetUpTableView ();
SetUpToolbar ();
SendButton.TouchUpInside += OnSendClicked;
TextView.Started += OnTextViewStarted;
TextView.Changed += OnTextChanged;
//register for an event
dataManager.getMessageBus().Register (MessageHandler);
}
catch(Exception ex)
{
Console.WriteLine(ex.Message + ex.StackTrace);
}
}
/// <summary>
/// Gets the message handler.
/// </summary>
/// <value>The message handler.</value>
public MessageBusEventHandler MessageHandler {
get
{
mEvHandler = new MessageBusEventHandler () {
EventId = kEventID,
EventAction = MessageBusEventHandler,
};
return mEvHandler;
}
}
/// <summary>
/// Messages the bus event handler.
/// </summary>
/// <param name="sender">Sender.</param>
/// <param name="evnt">Evnt.</param>
public void MessageBusEventHandler (object sender, MessageBusEvent evnt)
{
try{
//extract the data
var messageSender = evnt.Data [0] as String;
var message = evnt.Data [1] as String;
//execute on the UI thread
BeginInvokeOnMainThread (() => {
//post to the output box
if(messageSender.Trim().Equals(recipientUserID))
{
var msg = new ChatMessage
{
Type = MessageType.Incoming,
Text = message.Trim ()
};
messages.Add (msg);
tableView.InsertRows (new NSIndexPath[] { NSIndexPath.FromRowSection (messages.Count - 1, 0) }, UITableViewRowAnimation.None);
ScrollToBottom (true);
}
});
}catch(Exception ex)
{
Console.WriteLine (ex.Message + ex.StackTrace);
}
}
}