iOS定时任务

定时任务可以使用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.jianshu.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];

注:以上有什么不对的地方,还请大家指出.共同进步啊!

你可能感兴趣的:(iOS定时任务)