- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
// Override point for customization after application launch.
self.isActive = YES;
// 設置通知的類型可以為彈窗提示,聲音提示,應用圖標數字提示
UIUserNotificationSettings *setting = [UIUserNotificationSettings settingsForTypes:UIUserNotificationTypeBadge | UIUserNotificationTypeSound | UIUserNotificationTypeAlert categories:nil];
// 授權通知
[[UIApplication sharedApplication] registerUserNotificationSettings:setting];
[[UIApplication sharedApplication] cancelAllLocalNotifications];
return YES;
}
- (void)application:(UIApplication *)application didReceiveLocalNotification:(UILocalNotification *)notification {
if (self.isActive) {
UIAlertController * alert = [UIAlertController alertControllerWithTitle:@"溫馨提示" message:notification.alertBody preferredStyle:UIAlertControllerStyleAlert];
UIAlertAction *okAction = [UIAlertAction actionWithTitle:@"確定" style:UIAlertActionStyleDefault handler:nil];
[alert addAction:okAction];
[self.window.rootViewController presentViewController:alert animated:YES completion:nil];
}
}
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
dateFormatter.dateFormat = @"yyyy-MM-dd";
NSDate *date = [dateFormatter dateFromString:@"2018-08-27"];
[self localNotification:date];
}
- (void)localNotification:(NSDate *)date {
NSTimeInterval targetTimeInterval = [date timeIntervalSince1970];
NSTimeInterval beyond = [[NSDate date] timeIntervalSince1970];
// 提前 7天
NSTimeInterval sevenDayTimeInterval = targetTimeInterval - (60 * 60 * 24 * 7) + (60 * 60 * 9);
// 提前 3天
NSTimeInterval threeDayTimeInterval = targetTimeInterval - (60 * 60 * 24 * 3) + (60 * 60 * 9);
// 提前 1天
NSTimeInterval oneDayTimeInterval = targetTimeInterval - (60 * 60 * 24 * 1) + (60 * 60 * 9);
// 計算是否超過某天
if ((beyond - sevenDayTimeInterval) <= 0) {
[self addLocalNotification:sevenDayTimeInterval content:@"qi"];
}
if ((beyond - threeDayTimeInterval) <= 0) {
[self addLocalNotification:threeDayTimeInterval content:@"san"];
}
if ((beyond - oneDayTimeInterval) <= 0) {
[self addLocalNotification:oneDayTimeInterval content:@"yi"];
}
}
- (void)addLocalNotification:(NSTimeInterval)timeInterval content:(NSString *)content {
NSDate *fireDate = [NSDate dateWithTimeIntervalSince1970:timeInterval];
UILocalNotification *localNotification = [[UILocalNotification alloc] init];
localNotification.alertBody = content;
localNotification.fireDate = fireDate;
localNotification.soundName = UILocalNotificationDefaultSoundName;
[[UIApplication sharedApplication] scheduleLocalNotification:localNotification];
}