iOS 推送通知分为本地推送和远程推送通知,远程推送通知就相似于咱们平时使用微信时,即便锁屏了,也能收到好友发送给咱们的消息,而后在主屏幕显示一个alertview,远程推送须要远程服务端的支持,比较复杂. 本地推送相对比较简单,不须要服务端的支持。 微信
本地通知是NSLocalNotification 实现的,经过实例化一个NSLocalNotification类型的通知,同时设置通知的fireDate 属性,即通知的触发时间;设置timeZone属性,即时区;设置alertBody,显示的内容;设置alertAction;设置soundName,即推送发生时的声音;设置applicationIconBadgeNumber,即图标上的数字;设置userInfo属性,该属性是一个NSDictionary类型的变量。而后在使用UIApplication 的 实例方法scheduleLocalNotification:或 presentLocalNotificationNow: 推送通知。 app
在Appdelegate的- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions中添加以下代码: spa
NSDate * itemDate = [NSDate date]; UILocalNotification * localNotif = [[UILocalNotification alloc] init]; if(localNotif == nil) return ; localNotif.fireDate = [itemDate dateByAddingTimeInterval: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 dictionaryWithObjectsAndKeys:item.eventName,ToDoItemKey,@"Local Push reveived while running",MessageTitleKey ,nil]; localNotif.userInfo = infoDict; [[UIApplication sharedApplication] scheduleLocalNotification:localNotif]; NSLog(@"scheduledLocalNotifications are %@",[[UIApplication sharedApplication] scheduledLocalNotifications]);当应用程序收到本地推送通知是发调用Appdelegate的 -( void )application:( UIApplication *)application didReceiveLocalNotification:( UILocalNotification *)notification方法,在该方法中显示通知的内容:
-(void)application:(UIApplication *)application didReceiveLocalNotification:(UILocalNotification *)notification { NSLog(@"application : didReceiveLocalNotificaiton:"); NSString * itemName = [notification.userInfo objectForKey:ToDoItemKey]; NSString * messageTitle = [notification.userInfo objectForKey:MessageTitleKey]; [self _showAlert:itemName withTitle:messageTitle]; NSLog(@"Receive Local Notification while the app is still running ..."); NSLog(@"current notification is %@",notification); application.applicationIconBadgeNumber = notification.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]; }