曜日指定でローカル通知登録
iPhoneアプリ「めざまし天気」を申請中でして。
その中でちょっと苦労したぜな箇所を書いておきます。
曜日を指定してローカル通知を登録する
//通知登録 + (void) registerNotification { //全ての通知をキャンセル [[UIApplication sharedApplication] cancelAllLocalNotifications]; //1:日曜日〜7:土曜日で指定 ※ここでは例として日、月、水を指定 NSArray *weekAry = @[@1,@2,@4]; //通知時間生成 NSCalendar *calendar = [NSCalendar currentCalendar]; NSInteger repeart = 30;//繰り返し日数 NSDate *today = [NSDate date];//今日 NSDate *date; NSDateComponents *componentsForFireDate; for (int i = 0; i < repeart; i++) { date = [today dateByAddingTimeInterval:i * 24 * 60 * 60]; componentsForFireDate = [calendar components:(NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit | NSWeekdayCalendarUnit) fromDate:date]; //8:30を指定 [componentsForFireDate setHour:8]; [componentsForFireDate setMinute:30] ; [componentsForFireDate setSecond:0] ; NSDate *fireDateOfNotification = [calendar dateFromComponents: componentsForFireDate]; if ([weekAry containsObject:[NSNumber numberWithInteger:componentsForFireDate.weekday]]) { if ([[NSDate date] compare:fireDateOfNotification] == NSOrderedAscending) {//今より未来であること UILocalNotification *notification = [[UILocalNotification alloc] init]; notification.fireDate = fireDateOfNotification; //年月日・曜日を指定 notification.timeZone = [NSTimeZone defaultTimeZone]; notification.alertBody = @"通知のメッセージ"; //メッセージ notification.alertAction = @"通知のタイトル"; //タイトル notification.soundName = @"sampleMusic.caf"; //通知音指定 // 通知を登録する [[UIApplication sharedApplication] scheduleLocalNotification:notification]; } } } }
ポイント
1.前回登録したローカル通知を全部削除しておきます。
[[UIApplication sharedApplication] cancelAllLocalNotifications];
2.曜日を指定する時はforなどで回して判定する必要がある。
毎日だと判定なしでrepeatIntervalでいいのですが、曜日指定だと回さないといけない。
3.通知音は30秒以内
ソースコードとは関係ありませんが、通知音は30秒以内でないといけません。
越えると勝手にデフォルトのテロン♪に変えられます。