Local Notification Sample Code (OS 4.0 only)
Categories: iPhone on Jun.13, 2010
Start a new Window-based Application Project called LocalPush
Add an instance variable bgTask in LocalPushAppDelegate
Download Sample + 2 books “iPhoneMemoryManagementFinalVersion” and “ES 2.0 Programming Guide”
1 2 3 4 |
It will fire up a Local Notification to remind you one min before the event which is 2 minutes due from now
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 | // // LocalPushAppDelegate.m // LocalPush // @interface ToDoItem : NSObject { NSInteger year; NSInteger month; NSInteger day; NSInteger hour; NSInteger minute; NSInteger second; NSString *eventName; } @property (nonatomic, readwrite) NSInteger year; @property (nonatomic, readwrite) NSInteger month; @property (nonatomic, readwrite) NSInteger day; @property (nonatomic, readwrite) NSInteger hour; @property (nonatomic, readwrite) NSInteger minute; @property (nonatomic, readwrite) NSInteger second; @property (nonatomic, copy) NSString *eventName; @end @implementation ToDoItem @synthesize year, month, day, hour, minute, second, eventName; @end #import "LocalPushAppDelegate.h" @implementation LocalPushAppDelegate @synthesize window; #define ToDoItemKey @"EVENTKEY1" #define MessageTitleKey @"MSGKEY1" - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions { NSLog(@"application: didFinishLaunchingWithOptions:"); // Override point for customization after application launch UILocalNotification *localNotif = [launchOptions objectForKey:UIApplicationLaunchOptionsLocalNotificationKey]; if (localNotif) { NSString *itemName = [localNotif.userInfo objectForKey:ToDoItemKey]; // [viewController displayItem:itemName]; // custom method application.applicationIconBadgeNumber = localNotif.applicationIconBadgeNumber-1; NSLog(@"has localNotif %@",itemName); } else { [[UIApplication sharedApplication] cancelAllLocalNotifications]; NSDate *now = [NSDate date]; NSLog(@"now is %@",now); NSDate *scheduled = [now dateByAddingTimeInterval:120] ; //get x minute after NSCalendar *calendar = [NSCalendar currentCalendar]; unsigned int unitFlags = NSYearCalendarUnit|NSMonthCalendarUnit|NSDayCalendarUnit|NSHourCalendarUnit|NSMinuteCalendarUnit; NSDateComponents *comp = [calendar components:unitFlags fromDate:scheduled]; NSLog(@"scheduled is %@",scheduled); ToDoItem *todoitem = [[ToDoItem alloc] init]; todoitem.day = [comp day]; todoitem.month = [comp month]; todoitem.year = [comp year]; todoitem.hour = [comp hour]; todoitem.minute = [comp minute]; todoitem.eventName = @"Testing Event"; [self scheduleNotificationWithItem:todoitem interval:1]; NSLog(@"scheduleNotificationWithItem"); } [window makeKeyAndVisible]; return YES; } - (void)application:(UIApplication *)application didReceiveLocalNotification:(UILocalNotification *)notif { NSLog(@"application: didReceiveLocalNotification:"); NSString *itemName = [notif.userInfo objectForKey:ToDoItemKey]; NSString *messageTitle = [notif.userInfo objectForKey:MessageTitleKey]; // [viewController displayItem:itemName]; // custom method [self _showAlert:itemName withTitle:messageTitle]; NSLog(@"Receive Local Notification while the app is still running..."); NSLog(@"current notification is %@",notif); application.applicationIconBadgeNumber = notif.applicationIconBadgeNumber-1; } - (void) _showAlert:(NSString*)pushmessage withTitle:(NSString*)title { UIAlertView* alertView = [[UIAlertView alloc] initWithTitle:title message:pushmessage delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil]; [alertView show]; if (alertView) { [alertView release]; } } - (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 dateByAddingTimeInterval:-(minutesBefore*60)]; NSLog(@"fireDate is %@",localNotif.fireDate); 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]; NSDictionary *infoDict = [NSDictionary dictionaryWithObjectsAndKeys:item.eventName,ToDoItemKey, @"Local Push received while running", MessageTitleKey, nil]; localNotif.userInfo = infoDict; [[UIApplication sharedApplication] scheduleLocalNotification:localNotif]; NSLog(@"scheduledLocalNotifications are %@", [[UIApplication sharedApplication] scheduledLocalNotifications]); [localNotif release]; } - (NSString *) checkForIncomingChat { return @"javacom"; }; - (void)applicationDidEnterBackground:(UIApplication *)application { NSLog(@"Application entered background state."); // UIBackgroundTaskIdentifier bgTask is instance variable NSAssert(self->bgTask == UIBackgroundTaskInvalid, nil); bgTask = [application beginBackgroundTaskWithExpirationHandler: ^{ dispatch_async(dispatch_get_main_queue(), ^{ [application endBackgroundTask:self->bgTask]; self->bgTask = UIBackgroundTaskInvalid; }); }]; 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 Msg", nil); localNotif.soundName = @"alarmsound.caf"; localNotif.applicationIconBadgeNumber = 1; NSDictionary *infoDict = [NSDictionary dictionaryWithObjectsAndKeys:@"Your Background Task works",ToDoItemKey, @"Message from javacom", MessageTitleKey, nil]; localNotif.userInfo = infoDict; [application presentLocalNotificationNow:localNotif]; [localNotif release]; friend = nil; break; } } } [application endBackgroundTask:self->bgTask]; self->bgTask = UIBackgroundTaskInvalid; }); } - (void)dealloc { [window release]; [super dealloc]; } @end |
Similar posts:


July 21st, 2010 on 1:59 pm
А можно код представить в более удобном виде? Или хотя бы прикрепить к сообщению текстовый файл А то и цифры сбоку и по ширине не влазит, хотя монитор 22\"
September 3rd, 2010 on 6:39 pm
thanks!
this is just what I needed, a nice clear example.
/paul