LoginSignup
41
41

More than 5 years have passed since last update.

iOSで○日後の狙った時間にローカル通知を出す!

Last updated at Posted at 2014-04-04

ローカル通知の例はいろいろあるけど、何日後に出すってのがほとんど。
何日後の何時にだしたいんだ! 俺は!
ということで作ってみました。
以下を組み込んで、ローカル通知を設定したい場所で呼び出せばOK!

rocalNotification.m

- (void)viewLocalNotificationDidAppear
{

    /*--設定値を宣言するよ--*/
    int targetDay = 4;//何日後に出すか
    int targetHour = 12;//何時に出すか


    /*--ローカル通知を削除するよ--*/
    //バッチを0にするよ
    [UIApplication sharedApplication].applicationIconBadgeNumber = 0;

    //このアプリ名義で登録しているローカル通知を削除するよ
    [[UIApplication sharedApplication] cancelAllLocalNotifications];


    /*--日時操作に必要なもろもろ用意--*/
    //現在日時を取得するよ(標準日時だよ)
    NSDate *today = [NSDate date]; 

    //日付操作に必要なカレンダーを作成するよ。
    NSCalendar *cal = [NSCalendar currentCalendar];

    //日付を取り出しやすくするコンポーネントを作成するよ。
    NSDateComponents *comps = [[NSDateComponents alloc] init];

    /*--指定の日付、時間に通知するロジック--*/
    //タイムゾーンをiPhoneで指定したものに変更するよ
    [comps setTimeZone:[NSTimeZone systemTimeZone]];

    /*現在日時をカレンダーを通して、年|月|日に分解して
    **コンポーネントに登録するよ
    **時分秒はいらないので登録しないよ
    **登録しなかったら0で登録されるよ
    */
    comps = [cal components:(NSYearCalendarUnit   |
                             NSMonthCalendarUnit  |
                             NSDayCalendarUnit)
                   fromDate:today];

    //コンポーネントに入れた日付に◯日後を追加するよ
    targetDay += comps.day;

    //日時をコンポーネントにセットし直すよ
    [comps setDay:targetDay];
    [comps setHour:targetHour];

    //コンポーネントにセットした日時を標準日時に訳しなおすよ
    NSDate *date = [cal dateFromComponents:comps];
    NSLog(@"date:%@",date);


    /*--通知を作ってセットするよ--*/
    //通知を作るよ
    UILocalNotification *notification = [[UILocalNotification alloc]init];

    //通知に時間関係をいろいろセットするよ
    notification.fireDate = date;
    notification.repeatInterval = NSWeekCalendarUnit;
    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];

}
41
41
1

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
41
41