2

ローカル通知の追加をテストしたい。毎日/毎時繰り返したい。どうやってやるの?

NSCalendar *calendar = [NSCalendar autoupdatingCurrentCalendar];

 // Get the current date
    NSDate *now = [NSDate date];

 // Break the date up into components
NSDateComponents *dateComponents = [calendar components:( NSYearCalendarUnit |       NSMonthCalendarUnit |  NSDayCalendarUnit )
           fromDate:now];

NSDateComponents *timeComponents = [calendar components:( NSHourCalendarUnit | NSMinuteCalendarUnit | NSSecondCalendarUnit)
           fromDate:now];


 // Set up the fire time
NSDateComponents *dateComps = [[NSDateComponents alloc] init];

[dateComps setDay:[dateComponents day]];
[dateComps setMonth:[dateComponents month]];
[dateComps setYear:[dateComponents year]];

[dateComps setHour:[timeComponents hour]];
 [dateComps setMinute:[timeComponents minute]];
 [dateComps setSecond:[timeComponents second]+10];

 // Notification will fire in one minute

NSDate *itemDate = [calendar dateFromComponents:dateComps];
[dateComps release];

UILocalNotification *localNotif = [[UILocalNotification alloc] init];
if (localNotif == nil)
    return;

localNotif.fireDate = itemDate;
localNotif.timeZone = [NSTimeZone defaultTimeZone];

 // Notification details
localNotif.alertBody = @"Hello World";

 // Set the action button
localNotif.alertAction = @"View";
localNotif.soundName = UILocalNotificationDefaultSoundName;

applicationIconBadgeNumber++;

localNotif.applicationIconBadgeNumber = applicationIconBadgeNumber;

 // Schedule the notification
[[UIApplication sharedApplication] scheduleLocalNotification:localNotif];
[localNotif release];
4

4 に答える 4

12

毎日の特定の時間に通知を設定する場合は、通知のrepeatIntervalプロパティを設定する必要があります。iOSはそれを処理します。通知については独自のものです。この1行を追加するだけです...見逃しました。それ以外の場合、コードは問題なく機能します。

notif.repeatInterval = NSDayCalendarUnit;
于 2011-10-18T07:12:14.470 に答える
2

dateByAddingComponents:toDate:options: を使用すると、コードがはるかに簡単になります。

(dateByAddingTimeInterval: タイムゾーンの変更など、カレンダーを適切に処理しません。)

繰り返したい場合は、いくつか追加するか、アプリを次に起動するときに再度追加する必要があると思います。そうしないと、毎秒繰り返される通知が非常に煩わしくなります。

于 2010-08-06T19:17:48.040 に答える
2

このチュートリアルをチェックしてください: http://useyourloaf.com/blog/2010/9/13/repeating-an-ios-local-notification.html

于 2010-09-22T11:55:10.220 に答える
1
UILocalNotification *localNotif = [[UILocalNotification alloc] init];
if (localNotif == nil) return;

NSDate *fireTime = [[NSDate date]   dateByAddingTimeInterval:900]; // 15 minutes

localNotif.fireDate = fireTime;
localNotif.alertBody = @"15 min reached";
localNotif.repeatInterval=kCFCalendarUnitMinute;
[[UIApplication sharedApplication] scheduleLocalNotification:localNotif];
于 2012-07-31T10:56:29.747 に答える