- 在IOS8下沒(méi)有注冊(cè)奢方,所以需要額外添加對(duì)IOS8的注冊(cè)方法
第一步:注冊(cè)本地通知
// 設(shè)置本地通知
+ (void)registerLocalNotification:(NSInteger)alertTime {
UILocalNotification *notification = [[UILocalNotification alloc] init];
// 設(shè)置觸發(fā)通知的時(shí)間
NSDate *fireDate = [NSDate dateWithTimeIntervalSinceNow:alertTime];
NSLog(@"fireDate=%@",fireDate);
notification.fireDate = fireDate;
// 時(shí)區(qū)
notification.timeZone = [NSTimeZone defaultTimeZone];
// 設(shè)置重復(fù)的間隔
notification.repeatInterval = kCFCalendarUnitSecond;
// 通知內(nèi)容
notification.alertBody = @"該起床了...";
notification.applicationIconBadgeNumber = 1;
// 通知被觸發(fā)時(shí)播放的聲音
notification.soundName = UILocalNotificationDefaultSoundName;
// 通知參數(shù)
NSDictionary *userDict = [NSDictionary dictionaryWithObject:@"開始學(xué)習(xí)iOS開發(fā)了" forKey:@"key"];
notification.userInfo = userDict;
// ios8后哮内,需要添加這個(gè)注冊(cè),才能得到授權(quán)
if ([[UIApplication sharedApplication] respondsToSelector:@selector(registerUserNotificationSettings:)]) {
UIUserNotificationType type = UIUserNotificationTypeAlert | UIUserNotificationTypeBadge | UIUserNotificationTypeSound;
UIUserNotificationSettings *settings = [UIUserNotificationSettings settingsForTypes:type
categories:nil];
[[UIApplication sharedApplication] registerUserNotificationSettings:settings];
// 通知重復(fù)提示的單位,可以是天钝域、周、月
notification.repeatInterval = NSCalendarUnitDay;
} else {
// 通知重復(fù)提示的單位妥箕,可以是天连躏、周萨惑、月
notification.repeatInterval = NSDayCalendarUnit;
}
// 執(zhí)行通知注冊(cè)
[[UIApplication sharedApplication] scheduleLocalNotification:notification];
}
第二步:處理通知,這個(gè)是在appdelegate中的代理 方法回調(diào)
// 本地通知回調(diào)函數(shù)仇矾,當(dāng)應(yīng)用程序在前臺(tái)時(shí)調(diào)用
- (void)application:(UIApplication *)application didReceiveLocalNotification:(UILocalNotification *)notification {
NSLog(@"noti:%@",notification);
// 這里真實(shí)需要處理交互的地方
// 獲取通知所帶的數(shù)據(jù)
NSString *notMess = [notification.userInfo objectForKey:@"key"];
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"本地通知(前臺(tái))"
message:notMess
delegate:nil
cancelButtonTitle:@"OK"
otherButtonTitles:nil];
[alert show];
// 更新顯示的徽章個(gè)數(shù)
NSInteger badge = [UIApplication sharedApplication].applicationIconBadgeNumber;
badge--;
badge = badge >= 0 ? badge : 0;
[UIApplication sharedApplication].applicationIconBadgeNumber = badge;
// 在不需要再推送時(shí)庸蔼,可以取消推送
[HomeViewController cancelLocalNotificationWithKey:@"key"];
}
第三步:在需要的時(shí)候取消某個(gè)推送
// 取消某個(gè)本地推送通知
+ (void)cancelLocalNotificationWithKey:(NSString *)key {
// 獲取所有本地通知數(shù)組
NSArray *localNotifications = [UIApplication sharedApplication].scheduledLocalNotifications;
for (UILocalNotification *notification in localNotifications) {
NSDictionary *userInfo = notification.userInfo;
if (userInfo) {
// 根據(jù)設(shè)置通知參數(shù)時(shí)指定的key來(lái)獲取通知參數(shù)
NSString *info = userInfo[key];
// 如果找到需要取消的通知,則取消
if (info != nil) {
[[UIApplication sharedApplication] cancelLocalNotification:notification];
break;
}
}
}
}
示例圖:
test.png
demo.png