iOS本地推送简单实现代码
本文为大家分解介绍了iOS本地推送代码的三步骤,供大家参考,具体内容如下
第一步:创建本地推送
//创建一个本地推送
UILocalNotification*notification=[[[UILocalNotificationalloc]init]autorelease];
//设置10秒之后
NSDate*pushDate=[NSDatedateWithTimeIntervalSinceNow:10];
if(notification!=nil){
//设置推送时间
notification.fireDate=pushDate;
//设置时区
notification.timeZone=[NSTimeZonedefaultTimeZone];
//设置重复间隔
notification.repeatInterval=kCFCalendarUnitDay;
//推送声音
notification.soundName=UILocalNotificationDefaultSoundName;
//推送内容
notification.alertBody=@"推送内容";
//显示在icon上的红色圈中的数子
notification.applicationIconBadgeNumber=1;
//设置userinfo方便在之后需要撤销的时候使用
NSDictionary*info=[NSDictionarydictionaryWithObject:@"name"forKey:@"key"];
notification.userInfo=info;
//添加推送到UIApplication
UIApplication*app=[UIApplicationsharedApplication];
[appscheduleLocalNotification:notification];
}
第二步:接收本地推送
-(void)application:(UIApplication*)applicationdidReceiveLocalNotification:(UILocalNotification*)notification{
UIAlertView*alert=[[UIAlertViewalloc]initWithTitle:@"iWeibo"message:notification.alertBodydelegate:nilcancelButtonTitle:@"确定"otherButtonTitles:nil];
[alertshow];
//图标上的数字减1
application.applicationIconBadgeNumber-=1;
}
第三步:解除本地推送
//获得UIApplication
UIApplication*app=[UIApplicationsharedApplication];
//获取本地推送数组
NSArray*localArray=[appscheduledLocalNotifications];
//声明本地通知对象
UILocalNotification*localNotification;
if(localArray){
for(UILocalNotification*notiinlocalArray){
NSDictionary*dict=noti.userInfo;
if(dict){
NSString*inKey=[dictobjectForKey:@"key"];
if([inKeyisEqualToString:@"对应的key值"]){
if(localNotification){
[localNotificationrelease];
localNotification=nil;
}
localNotification=[notiretain];
break;
}
}
}
//判断是否找到已经存在的相同key的推送
if(!localNotification){
//不存在初始化
localNotification=[[UILocalNotificationalloc]init];
}
if(localNotification){
//不推送取消推送
[appcancelLocalNotification:localNotification];
[localNotificationrelease];
return;
}
}
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持毛票票。
