Calling A Method At Specific Time Every Day

前端 未结 3 1925
臣服心动
臣服心动 2020-12-06 08:34

My app runs constantly in kiosk mode. Once every 24 hours at a specific time I need to sync some data from core data to a web service.

I know how to do the sync p

3条回答
  •  醉话见心
    2020-12-06 08:48

    Figured this out thanks to prompts from @lakesh. Posting solution in the case it helps somebody because I found NSNotification examples very difficult to understand at first.

    In my main view controller I added the following method:

    - (void)scheduleNotification
    {
    [[UIApplication sharedApplication] cancelAllLocalNotifications];
    
    UILocalNotification *notif = [[UILocalNotification alloc] init];
    
    NSCalendar *calendar = [NSCalendar currentCalendar];
    NSDateComponents *components = [[NSDateComponents alloc] init];
    
    components = [[NSCalendar currentCalendar] components:NSDayCalendarUnit | NSMonthCalendarUnit | NSYearCalendarUnit fromDate:[NSDate date]];
    
    NSInteger day = [components day];
    NSInteger month = [components month];
    NSInteger year = [components year];
    
    [components setDay: day];
    [components setMonth: month];
    [components setYear: year];
    [components setHour: 02];
    [components setMinute: 45];
    [components setSecond: 0];
    [calendar setTimeZone: [NSTimeZone systemTimeZone]];
    NSDate *dateToFire = [calendar dateFromComponents:components];
    
    notif.fireDate = dateToFire;
    notif.timeZone = [NSTimeZone systemTimeZone];
    notif.repeatInterval = NSDayCalendarUnit;
    
    [[UIApplication sharedApplication] scheduleLocalNotification:notif];
    }
    

    This sets a fire date for the notification of today at 02:45 am and recurs daily.

    In viewDidLoad in my view controller I call the above method:

    [self scheduleNotification];
    

    In the appdelegate I do the following:

    - (void)application:(UIApplication *)application didReceiveLocalNotification:    (UILocalNotification *)notification
    {   
    application.applicationIconBadgeNumber = 0;
        //call your method that you want to do something in your app
    } 
    

提交回复
热议问题