定時任務可以使用NSTimer.也可以使用本地推送UILocalNotification.
1.NSTimer
設定個時間就行了.(使用NSTimer的block初始化,要注意防止循環引用)
NSTimer *timer = [NSTimer timerWithTimeInterval:66 repeats:YES block:^(NSTimer * _Nonnull timer) {
//執行你的代碼
}];
當然也可以指定一個時間觸發.比如下方指定每天的某一點觸發(首先保證程序不被kill掉的情況下).
- (void)timingTask {
//首先獲取一個時間
NSDate *date = [NSDate date];
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"yyyy.MM.dd"];
NSString *dateStr = [dateFormatter stringFromDate:date];
//設置一個時間點. 比如 16:16:16
NSString *newDateStr = [NSString stringWithFormat:@"%@ 16:16:16", dateStr];
[dateFormatter setDateFormat:@"yyyy.MM.dd HH:mm:ss"];
NSDate *newDate = [dateFormatter dateFromString:newDateStr];
//然后初始化一個NSTimer.
//一天的秒數是86400.然后設置重復repeats:YES.指定執行哪個方法.
//最后添加到runloop就行了.從你運行代碼的當天起,就開始執行了.
NSTimer *timer = [[NSTimer alloc] initWithFireDate:newDate interval:10 target:self selector:@selector(timeTrigger) userInfo:nil repeats:YES];
[[NSRunLoop currentRunLoop] addTimer:timer forMode:NSDefaultRunLoopMode];
}
- (void)timeTrigger {
NSLog(@"觸發了");
}
2.UILocalNotification(類似鬧鐘的東西)
①.定時推送(http://www.lxweimin.com/p/3ed1db4fa538)
②.類似鬧鐘的(每天定時任務)
- (void)alarmClock {
//首先獲取一個時間
NSDate *date = [NSDate date];
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"yyyy.MM.dd"];
NSString *dateStr = [dateFormatter stringFromDate:date];
//設置一個時間點. 比如 16:16:16
NSString *newDateStr = [NSString stringWithFormat:@"%@ 16:16:16", dateStr];
[dateFormatter setDateFormat:@"yyyy.MM.dd HH:mm:ss"];
NSDate *newDate = [dateFormatter dateFromString:newDateStr];
//然后創建個本地推送.
UILocalNotification *localNotification = [[UILocalNotification alloc] init];
if (localNotification) {
localNotification.fireDate = newDate;
localNotification.timeZone = [NSTimeZone defaultTimeZone];
localNotification.repeatInterval = NSCalendarUnitDay;//設置每天重復
localNotification.alertTitle = @"鬧鐘";
localNotification.alertBody = @"懶蟲起床了!~~";
localNotification.alertAction = @"再睡會~";
//如果有需要傳的東西可以設置一下userInfo
localNotification.userInfo = @{@"key": @"value"};
[[UIApplication sharedApplication] scheduleLocalNotification:localNotification];
}
}
最后你每天就可以收到推送了.當然你也可以設置一下音頻,
localNotification.soundName = UILocalNotificationDefaultSoundName;
但是如果需要將本地推送刪除或者替換掉.需要從本地通知數組中遍歷查找.然后再進行操作.
- (void)searchMyLocalNotification {
NSArray *locArr = [[UIApplication sharedApplication] scheduledLocalNotifications];
for (UILocalNotification *localNotification in locArr) {
NSDictionary *userInfo = localNotification.userInfo;
//你可以通過userInfo中的數據(key和value)來判斷是不是你想要的通知
//然后你可以刪除此通知,或者將此通知替換掉
}
}
刪除本地通知的代碼
[[UIApplication sharedApplication] cancelLocalNotification:localNotification];
注:以上有什么不對的地方,還請大家指出.共同進步啊!