XamarinでApple Watchアプリを作る(その5)- 通知
通知をWatchに出します。 Watchの主な使い方がこれですね。(これ以外の使い方が思いつかない)
通知が出てくれるのは、
- サーバーからのPush通知かアプリからのLocal Notificationを
- Watchを身に着けていて
- iPhoneがロックしている状態
で受信すると出ます。
Push通知は実験で行うには少しハードルが高いので今回はLocal Notificationで実験します。
Local Notificationを投げる
これはiPhoneアプリの事なのでググればいっぱい出てくるでしょう。
今回はアプリ起動後10秒で通知するようにだけします。
起動時に通知を許可してもらって
public override bool FinishedLaunching(UIApplication application, NSDictionary launchOptions) { var settings = UIUserNotificationSettings.GetSettingsForTypes( UIUserNotificationType.Alert | UIUserNotificationType.Badge | UIUserNotificationType.Sound , null); UIApplication.SharedApplication.RegisterUserNotificationSettings(settings); return true; }
ViewControllerのロード時に通知
public override void ViewDidLoad() { base.ViewDidLoad(); var notification = new UILocalNotification(); notification.FireDate = NSDate.Now.AddSeconds(10); notification.TimeZone = NSTimeZone.DefaultTimeZone; notification.AlertTitle = "Alert test"; notification.AlertAction = "Alert action"; notification.AlertBody = "test alert "; notification.SoundName = "default"; notification.UserInfo = NSDictionary.FromObjectAndKey(new NSString("UserInfo for notification"), new NSString("Notification")); UIApplication.SharedApplication.ScheduleLocalNotification(notification); }
XamarinのサンプルではSoundNameプロパティを指定してなかったんですが、これを指定しないとWatchで音がならないし振動もしてくれません。(通知は行きます)
試してみる
- iPhoneシミュレーター側でアプリを起動
- 急いでLockして10秒待つ
でちゃんと通知がWatchに出ます。 実機でやれば音が鳴って振動もします。
いきなり通知を出す
テストの度に毎回こんなことをするのは大変です。 ということでデバッガでいきなり通知を出します。
WatchApp1.WKExtensionプロジェクトの中にPushNotificationPayload.jsonというファイルが入っています。
Push通知の内容がjsonで記述されてますね。 内容はググって調べてください。
このjsonをWatchApp1.WKExtension→プロパティ→Debug→Notification Simulation Fileに指定します。
あとはシミュレーターの選択で~(Notification)を選択して
実行
先ほどのjsonが通知としてWatchに飛んでいきました。
やったね