在iOS中,本地通知非常適用于基于時(shí)間的行為.例如,有一個(gè)需求是讓用戶專(zhuān)注做某件事情一段時(shí)間. 時(shí)間到了后給個(gè)通知告知.實(shí)現(xiàn)這樣一個(gè)功能可以使用本地通知
實(shí)現(xiàn)如下效果:
本地通知實(shí)現(xiàn)步驟:
1.創(chuàng)建本地通知對(duì)象 ( UILocalNotification )
2.設(shè)置通知的屬性
3.讓?xiě)?yīng)用程序調(diào)用通知,使用UIApplication對(duì)象調(diào)用scheduleLocalNotification:方法
4.在iOS8.0之后,在調(diào)度通知之前需要使用 UIApplication的對(duì)象方法registerUserNotificationSettings:來(lái)請(qǐng)求用戶授權(quán)
代碼實(shí)現(xiàn)
定義本地通知對(duì)象屬性
/** 創(chuàng)建本地通知對(duì)象*/
@property (nonatomic,strong) UILocalNotification *lNotification;
懶加載
//懶加載
- (UILocalNotification *)lNotification{
if (!_lNotification) {
_lNotification = [[UILocalNotification alloc] init];
}
return _lNotification;
}
設(shè)置通知的屬性
/** 設(shè)置通知的內(nèi)容*/
self.lNotification.alertBody = @"時(shí)間到了";
/** 設(shè)置通知觸發(fā)開(kāi)始的時(shí)間*/
self.lNotification.fireDate = [NSDate dateWithTimeIntervalSinceNow:3];
/** 設(shè)置時(shí)區(qū)*/
self.lNotification.timeZone = [NSTimeZone defaultTimeZone];
/** 設(shè)置應(yīng)用圖標(biāo)右上角的數(shù)字*/
self.lNotification.applicationIconBadgeNumber = 1;
/** 設(shè)置通知的音效(只有真機(jī)有效)*/
self.lNotification.soundName = UILocalNotificationDefaultSoundName;
讓?xiě)?yīng)用程序調(diào)用通知
/** 讓?xiě)?yīng)用程序調(diào)用通知*/
[[UIApplication sharedApplication] scheduleLocalNotification:self.lNotification];
更新顯示徽章數(shù)方法
/** 更新顯示徽章數(shù)*/
[UIApplication sharedApplication].applicationIconBadgeNumber = 0;
在iOS8.0之后,在調(diào)度通知之前需要使用 UIApplication的對(duì)象方法registerUserNotificationSettings:來(lái)請(qǐng)求用戶授權(quán),該方法需要在**application: didFinishLaunchingWithOptions: **中實(shí)現(xiàn)
/**
* 在iOS8.0之后,在調(diào)度通知之前需要使用 UIApplication的對(duì)象方法registerUserNotificationSettings:來(lái)請(qǐng)求用戶授權(quán)
UIUserNotificationType:
UIUserNotificationTypeBadge 接收到通知可更改程序的應(yīng)用圖標(biāo)
UIUserNotificationTypeSound 接收到通知可播放聲音
UIUserNotificationTypeAlert 接收到通知提示內(nèi)容
*/
if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 8.0) {
UIUserNotificationSettings *settings = [UIUserNotificationSettings settingsForTypes:UIUserNotificationTypeBadge |UIUserNotificationTypeSound | UIUserNotificationTypeAlert categories:nil];
[[UIApplication sharedApplication] registerUserNotificationSettings:settings];
}
到此,可以實(shí)現(xiàn)本地通知功能.