Swift 3 - 即使应用程序在后台运行一个函数

ThB*_*hBM 0 background timer ios swift swift3

我的 iOS 应用程序遇到了问题。即使我的应用程序不在 iPhone 的前台,我也想每天运行一个函数。我尝试使用NSTimerObject 但如果我的应用程序在后台,它就不起作用。

我怎样才能做到这一点?

注意:我的函数将触发一个通知,该通知根据当天的不同而有所不同。

Pok*_*oke 5

Paulw11 是正确的。您可以使用后台刷新和本地通知。后台获取将被随机调用。每次调用时,本地通知都会重置。这段代码是Obj C,有点老了,但是概念是一样的。

-(void)application:(UIApplication *)application performFetchWithCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler  {


BackgroundFetch * fetch = [[BackgroundFetch alloc] init];

[fetch fetchNewDataWithCompletionHandler:^(UIBackgroundFetchResult result) {
    completionHandler(result);
} successDictionary:^(NSDictionary *responseDict) {

  // Schedule local notification, in this case it is 9am

   [[UIApplication sharedApplication] cancelAllLocalNotifications];

        UILocalNotification *notif = [[UILocalNotification alloc] init];

            NSCalendar *calendar = [NSCalendar currentCalendar];
            NSDateComponents *components = [[NSDateComponents alloc] init];

            components = [[NSCalendar currentCalendar] components:NSCalendarUnitDay | NSCalendarUnitMonth | NSCalendarUnitYear 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: 9];
            [components setMinute: 0];
            [components setSecond: 0];
            [calendar setTimeZone: [NSTimeZone systemTimeZone]];
            NSDate *dateToFire = [calendar dateFromComponents:components];

        notif.fireDate = dateToFire;
        notif.timeZone = [NSTimeZone systemTimeZone];
        notif.alertBody = [NSString stringWithFormat:@"%@: %@", responseDict[@"city"], responseDict[@"temp"]];

        [[UIApplication sharedApplication] scheduleLocalNotification:notif];
}
Run Code Online (Sandbox Code Playgroud)