酢ろぐ!

カレーが嫌いなスマートフォンアプリプログラマのブログ。

Xamarin.Macでローカル通知をおこなう

Xamarin.Macでローカル通知をおこないます。 コードを全て掲載すると冗長になってしまうのでgistへアップロードしておきました。

partial void buttonAction(NSObject sender)
{
    var dc = NSUserNotificationCenter.DefaultUserNotificationCenter;
    dc.Delegate = new UserNotificationCenterDelegate();

    var keys = new [] { "url" };
    var values = new object[] { "https://blog.ch3cooh.jp/" };
    var userInfo = NSDictionary.FromObjectsAndKeys(values, keys);

    var notification = new NSUserNotification();
    notification.Title = "タイトル";
    notification.Subtitle = "サブタイトル";
    notification.InformativeText = "本文";
    notification.UserInfo = userInfo;

    dc.DeliverNotification(notification);
}

class UserNotificationCenterDelegate : NSUserNotificationCenterDelegate
{
    public override void DidActivateNotification(
        NSUserNotificationCenter center, NSUserNotification notification)
    {
        //通知センターで該当の通知をタップした時の処理
    }
}

ボタンをタップするとbuttonActionが実行されて、通知センターへ通知をおこないます。

通知センターには下図のように通知が表示されます。

通知をタップして特定の処理を実行する

通知をタップして特定の処理を実行させることができます。

例えば、ユーザーが通知をタップするとブラウザを起動させる場合には、下記のように書くことができます。

class UserNotificationCenterDelegate : NSUserNotificationCenterDelegate
{
    public override void DidActivateNotification(NSUserNotificationCenter center, NSUserNotification notification)
    {
        var urlString = notification.UserInfo?["url"] as NSString;
        if (urlString != null)
        {
            var url = new NSUrl(urlString);
            NSWorkspace.SharedWorkspace.OpenUrl(url);
        }
    }
}