//.h
//注冊
+ (void)registerLocalNotification;
//推送
+ (UILocalNotification *)pushLocalNotificationFor:(NSString *)alertBody;
+ (UILocalNotification *)pushLocalNotificationFor:(NSString *)alertBody userInfo:(NSDictionary *)userInfo;
+ (UILocalNotification *)pushLocalNotificationFor:(NSString *)alertBody userInfo:(NSDictionary *)userInfo fireSinceNow:(NSTimeInterval)time;
//.m
//注冊
+ (void)registerLocalNotification {
//ios8之后注冊通知 和之前不一樣
#ifdef __IPHONE_8_0
//ios8? 注冊本地通知
if ([UIApplication instancesRespondToSelector:@selector(registerUserNotificationSettings:)]) {
UIUserNotificationSettings *noteSetting =[UIUserNotificationSettings settingsForTypes:UIUserNotificationTypeAlert|UIUserNotificationTypeBadge|UIUserNotificationTypeSound categories:nil];
[[UIApplication sharedApplication] registerUserNotificationSettings:noteSetting];
}
if ([[UIApplication sharedApplication]respondsToSelector:@selector(registerUserNotificationSettings:)]) {
UIUserNotificationSettings? ? *setting = [UIUserNotificationSettings settingsForTypes:UIUserNotificationTypeAlert | UIUserNotificationTypeBadge | UIUserNotificationTypeSound categories:nil];
[[UIApplication sharedApplication]registerUserNotificationSettings:setting];
}else {
UIRemoteNotificationType? myType = UIUserNotificationTypeAlert | UIUserNotificationTypeBadge | UIUserNotificationTypeSound;
[[UIApplication sharedApplication]registerForRemoteNotificationTypes:myType];
}
#else
#endif
}
//推送
+ (UILocalNotification *)pushLocalNotificationFor:(NSString *)alertBody {
//在ios下應用分為兩種不同的Notification種類
//1.本地? ? ? //2.遠程(APNS)
//本地? ? ? Notification 是由ios系統下NotificationManger統一管理.只需要將組裝好的本地通知對象添加到系統的Notification管理隊列,系統就會在指定的時間激發該通知
//本地通知? 只能在前臺和后臺觸發,不能在其他狀態下激發
//本地? 流程
//1.1創建一個本地通知對象
UILocalNotification? *localNotification = [[UILocalNotification alloc]init];
//調度
//1.2 時間上的調度
//fireDate 就是激發的準確時間
localNotification.fireDate = [NSDate? dateWithTimeIntervalSinceNow:1.0];
//timeZone 是通知激發的時間是否根據時區的改變而改變,如果是nil,通知會在一段時間后激發,而不是某一確切的時間被激發
//repeatInteval 被重復激發的時間,時間差會根據日歷單位,例如每周,如果不設置,將會被重復
//1.3 內容
localNotification.alertBody = kSTR(@"%@", alertBody);
//1.4其他內容
UIApplication? *app = [UIApplication sharedApplication];
app.applicationIconBadgeNumber ++;
//最后一步
//注冊
[[UIApplication sharedApplication]scheduleLocalNotification:localNotification];
return localNotification;
}
+ (UILocalNotification *)pushLocalNotificationFor:(NSString *)alertBody userInfo:(NSDictionary *)userInfo {
UILocalNotification? *mzLocalNotification = [self pushLocalNotificationFor:alertBody];
mzLocalNotification.userInfo = userInfo;
return mzLocalNotification;
}
+ (UILocalNotification *)pushLocalNotificationFor:(NSString *)alertBody userInfo:(NSDictionary *)userInfo fireSinceNow:(NSTimeInterval)time {
UILocalNotification? *mzLocalNotification = [self pushLocalNotificationFor:alertBody userInfo:userInfo];
mzLocalNotification.fireDate = [NSDate dateWithTimeIntervalSinceNow:time];
return mzLocalNotification;
}
謝謝閱讀!