テラシュールブログ

旧テラシュールウェアブログUnity記事。主にUnityのTipsやAR・VR、ニコニコ動画についてのメモを残します。

プッシュ通知で遊んでみる

唐突にローカル通知で遊ぶべきとのお告げが出てきたので、少し遊んでみた。やりたい事は、ローカル通知のバッジ(数字入りの赤丸)を変動させる的な事。

[Unity3D]ローカル通知を使う
http://terasur.blog.fc2.com/blog-entry-184.html
[Unity3D]続・ローカル通知を使う
http://terasur.blog.fc2.com/blog-entry-185.html

スクリーンショット 2012-11-18 1.08.21 スクリーンショット 2012-11-18 1.08.01

内容はpushボタンを押すと30秒後に通知する仕組み。複数回pushボタンを押した場合は、通知がくるたびにバッジの数が+1している風に見えるようにしている。
当然iOSでしか動かない。

なんでこんな事をしようと思ったのか分からないが、作ってしまったので一応メモ。

using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using System;

public class AlartCounter : MonoBehaviour {

List timeList = new List();

void OnApplicationPause(bool isPhause)
{
#if UNITY_IPHONE
if( isPhause )
{
int count = 0;
foreach( DateTime time in timeList)
{
count += 1;
LocalNotification notification = new LocalNotification();
notification.applicationIconBadgeNumber = count;
notification.fireDate = time;
notification.alertBody = time.ToString();

NotificationServices.ScheduleLocalNotification(notification);
}
}else{
LocalNotification notification = new LocalNotification();
notification.applicationIconBadgeNumber = -1;
NotificationServices.PresentLocalNotificationNow(notification);

NotificationServices.CancelAllLocalNotifications();
NotificationServices.ClearLocalNotifications();
}

#endif
}

void Update()
{
List removeTimeList = new List();

DateTime now = DateTime.Now;
foreach( DateTime time in timeList)
{
if( (time - now).TotalSeconds < 0)
removeTimeList.Add(time);
}

foreach( DateTime time in removeTimeList)
{
timeList.Remove(time);
}

}

void OnGUI()
{
if( GUILayout.Button("Push", GUILayout.MinHeight(80), GUILayout.MinWidth(300)))
timeList.Add( DateTime.Now.AddSeconds(30));

GUILayout.BeginVertical("Box");
{
foreach( DateTime time in timeList )
{
GUILayout.Label( (time - DateTime.Now).TotalSeconds.ToString("0.0"), GUILayout.MinHeight(30) );
}
}
GUILayout.EndVertical ();
}
}

やってる事は単純で、Pushを押した時に30秒後の時間を取得しておいて、アプリをホームボタンで中断したときに取得した時間の数だけ通知を配置しているだけ。
アプリを再会した時に通知を全部リセットするので、バッジの数が飛んだりしないようにしている。

実際はもうちょっと上手い方法がある気がする。timeListとかバッジの数をNotificationServicesから取得するとか。



本当に何でコレ作ったんだっけ・・・タイマーアプリでも作ろうと思ったのかな