LoginSignup
4
6

More than 5 years have passed since last update.

ローカル通知を日本時間で毎日行う場合

Last updated at Posted at 2017-04-05

概要

日本時間でローカル通知を毎日行う場合。
過去のtipsにはduplicateの関数や、定数が多かったので忘れないようにメモ。

ローカル通知とは

前提

  • 毎日6時にローカル通知を行う
  • 毎週の決まった曜日や、何週目指定でも可能
  • timeZoneをlocalTimeZoneに設定してやれば、設定はGMTと比較せずに素直に行えば良い
    //NSCalenderのインスタンス化(NSCalendarIdentifierGregorianで強制的に西暦で計算するようにする)
    NSCalendar *calendar = [[NSCalendar alloc]initWithCalendarIdentifier:NSCalendarIdentifierGregorian];
    //日付、時間の設定(作成)を行う
    NSDateComponents *comps = [[NSDateComponents alloc] init];
    //西暦を指定
    [comps setYear:2017];
    //月を指定
    [comps setMonth:4];
    //日を指定
    [comps setDay:6];
    //曜日を指定する場合(0が日曜日、1が月曜日、6が土曜日)
    //[comps setWeekday:5];
    //その月の何週目かに通知させる場合(例は2週目)
    //[comps setWeekdayOrdinal:2];
    //時間を指定(例は端末の設定タイムゾーンの6時)
    [comps setHour:6];
    //分を指定(例は0時)
    [comps setMinute:0];
    //NSDateに上記で設定した時間を挿入する。
    NSDate *date = [calendar dateFromComponents:comps];

    NSLog(@"[ログ]日時=%@", date);

    //現在の時刻から指定した時刻の長さを取得する。(秒単位で取得出来る。)
    NSTimeInterval span = [date timeIntervalSinceDate:[NSDate date]];
    NSLog(@"[ログ]現在時間との時差は%f秒",span);

    //全てのローカル通知を削除する(削除しないと過去のローカル通知に上書きされてしまうため)
    [[UIApplication sharedApplication] cancelAllLocalNotifications];

    //ローカル通知をさせるためのインスタンスを作成。
    UILocalNotification *notification = [[UILocalNotification alloc]init];

    //ローカル通知させる時間を設定する。ここで設定した時間に繰り返しローカル通知されるようになる。
    notification.fireDate = [[NSDate date] dateByAddingTimeInterval:span];
    //毎週アラームを通知させる。
    notification.repeatInterval = NSCalendarUnitDay; //1日おきに起動
    //時間をその端末のあるロケーションに合わせる。
    notification.timeZone = [NSTimeZone localTimeZone];
    //通知されたときに、アイコンの右上に数字を表示させる。
    notification.applicationIconBadgeNumber = 1; //バッジを表示させない場合はコメントアウト
    //ローカル通知されたときの文字を設定
    notification.alertBody = [NSString stringWithFormat:@"通知タイトル"];
    //通知されるときの音を指定
    notification.soundName = UILocalNotificationDefaultSoundName;
    //画面を閉じてた時にアラームが鳴った場合、スライドに表示させる文字を設定
    notification.alertAction = @"通知タイトル";
    NSDictionary *infoDict = [NSDictionary dictionaryWithObject:@"アプリを開く" forKey:@"EventKey"];
    notification.userInfo = infoDict;

    //作成したローカル通知をアプリケーションに登録
    [[UIApplication sharedApplication] scheduleLocalNotification:notification];

    //登録されているアラームを配列に格納
    NSArray *notifiyItems = [[UIApplication sharedApplication] scheduledLocalNotifications];
    //ローカル通知に登録されている件数を確認のため表示
    NSLog(@"登録件数は%d件",(int)[notifiyItems count]);
    for(UILocalNotification *notifiy in notifiyItems){
        //ローカル通知に登録されている、alertBodyの文字列を表示する。
        NSLog(@"[ログ]:%@",[notifiy alertBody]);
    }

4
6
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
4
6