說到推送,項目開發(fā)中有可能會使用定時推送.類似鬧鐘,或者提醒事項,定個時間發(fā)起推送.
使用本地推送和普通推送一樣,也需要注冊推送通知.
在Appdelegate.m中的
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions;
方法中填寫下放代碼.
if ([UIApplication instancesRespondToSelector:@selector(registerUserNotificationSettings:)]){
[[UIApplication sharedApplication] registerUserNotificationSettings:[UIUserNotificationSettings settingsForTypes:UIUserNotificationTypeAlert|UIUserNotificationTypeBadge|UIUserNotificationTypeSound categories:nil]];
}
然后實現(xiàn)接受本地推送的方法
//接受處理本地推送
- (void)application:(UIApplication *)application didReceiveLocalNotification:(UILocalNotification *)notification NS_AVAILABLE_IOS(4_0) {
//使用UIAlertView顯示推送的消息
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:notification.alertTitle message:notification.alertBody delegate:self cancelButtonTitle:@"確定" otherButtonTitles:nil, nil];
[alert show];
}
好了,先在我們創(chuàng)建一個定時推送.
- (void)setUpLocalNotification:(NSString *)dateStr {
UILocalNotification *localNotification = [[UILocalNotification alloc] init];
if (localNotification == nil) {
return;
}
//處理時間字符串
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
formatter.dateFormat = @"yyyy-MM-dd HH:mm";
NSDate *fireDate = [formatter dateFromString:dateStr];
NSAssert(fireDate, @"dateStr類型不匹配,或者為nil");
//設(shè)置UILocalNotification
[localNotification setTimeZone:[NSTimeZone defaultTimeZone]];//設(shè)置時區(qū)
localNotification.fireDate = fireDate;//設(shè)置觸發(fā)時間
localNotification.repeatInterval = 0;//設(shè)置重復(fù)間隔
localNotification.alertBody = @"定時推送的信息";
localNotification.alertTitle = @"定時推送";
localNotification.soundName = UILocalNotificationDefaultSoundName;
//當(dāng)然你也可以調(diào)取當(dāng)前的氣泡,并且設(shè)置.也可以設(shè)置一個userInfo進(jìn)行傳遞信息
/*
[localNotification setApplicationIconBadgeNumber:66];
localNotification.applicationIconBadgeNumber += 1;
localNotification.userInfo = @{@"KEY" : @"VALUE"};
*/
[[UIApplication sharedApplication] scheduleLocalNotification:localNotification];
}
然后給定你的dateStr,就行了
注意的是:dateStr的類型需要和你的dateFormat類型相同,不然fireDate會為nil.