/如何创建设定一个Notification
- (
void
)scheduleNotificationWithItem:(ToDoItem *)item interval:(
int
)minutesBefore {
NSCalendar *calendar = [NSCalendar autoupdatingCurrentCalendar];
NSDateComponents *dateComps = [[NSDateComponents alloc] init];
[dateComps setDay:item.day];
[dateComps setMonth:item.month];
[dateComps setYear:item.year];
[dateComps setHour:item.hour];
[dateComps setMinute:item.minute];
NSDate *itemDate = [calendar dateFromComponents:dateComps];
[dateComps release];
UILocalNotification *localNotif = [[UILocalNotification alloc] init];
if
(localNotif == nil)
return
;
localNotif.fireDate = [itemDate addTimeInterval:-(minutesBefore*60)];
localNotif.timeZone = [NSTimeZone defaultTimeZone];
localNotif.alertBody = [NSString stringWithFormat:NSLocalizedString(@
"%@ in %i minutes."
, nil),
item.eventName, minutesBefore];
localNotif.alertAction = NSLocalizedString(@
"View Details"
, nil);
localNotif.soundName = UILocalNotificationDefaultSoundName;
localNotif.applicationIconBadgeNumber = 1;
NSDictionary *infoDict = [NSDictionary dictionaryWithObject:item.eventName forKey:ToDoItemKey];
localNotif.userInfo = infoDict;
[[UIApplication sharedApplication] scheduleLocalNotification:localNotif];
[localNotif release];
}
//程序运行在后台时候如何提交一个UILocalNotification。
- (
void
)applicationDidEnterBackground:(UIApplication *)application {
NSLog(@
"Application entered background state."
);
// bgTask is instance variable
NSAssert(self->bgTask == UIInvalidBackgroundTask, nil);
bgTask = [application beginBackgroundTaskWithExpirationHandler: ^{
dispatch_async(dispatch_get_main_queue(), ^{
[application endBackgroundTask:self->bgTask];
self->bgTask = UIInvalidBackgroundTask;
});
}];
dispatch_async(dispatch_get_main_queue(), ^{
while
([application backgroundTimeRemaining] > 1.0) {
NSString *
friend
= [self checkForIncomingChat];
if
(
friend
) {
UILocalNotification *localNotif = [[UILocalNotification alloc] init];
if
(localNotif) {
localNotif.alertBody = [NSString stringWithFormat:
NSLocalizedString(@
"%@ has a message for you."
, nil),
friend
];
localNotif.alertAction = NSLocalizedString(@
"Read Message"
, nil);
localNotif.soundName = @
"alarmsound.caf"
;
localNotif.applicationIconBadgeNumber = 1;
[application presentLocalNotificationNow:localNotif];
[localNotif release];
friend
= nil;
break
;
}
}
}
[application endBackgroundTask:self->bgTask];
self->bgTask = UIInvalidBackgroundTask;
});
}