iOS background fetch not working

荒凉一梦 提交于 2019-12-25 03:14:01

问题


I want to pull some data from server in every 30 min interval and set local notification to remind the user and i implemented below code to perform this operation.

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {


    [application setMinimumBackgroundFetchInterval:UIApplicationBackgroundFetchIntervalMinimum];
    return YES;
}

-(void)application:(UIApplication *)application performFetchWithCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler{
    NSString *value = [[NSUserDefaults standardUserDefaults]objectForKey:@"bgFetch"];

    if ([Utilities isInternetConnectionAvailable]) {
        if ([self.window.rootViewController isKindOfClass:[HomeViewController class]]){

            HomeViewController *homeController = (HomeViewController*)self.window.rootViewController;
            [homeController fetchDatawithCompletionHandler:^(UserData *userData, NSString *errorResponse) {
                if (userData) {
                    if (![homeController isNotificationAvailvableForTheData:userData]) {
                        [homeController scheduleLocalNotificationForUserData:userData];
                        completionHandler(UIBackgroundFetchResultNewData);
                    }
                }else{
                    completionHandler(UIBackgroundFetchResultFailed);
                }
            }];
        }else{
            completionHandler(UIBackgroundFetchResultNoData);
        }

    }else{
        completionHandler(UIBackgroundFetchResultFailed);
    }
}

I also enabled background fetch in capability and added the key "Required background modes" in plist. When i checked after few hours, no local notification is set. Where am i doing wrong ?


回答1:


I was facing the same issue. Whenever I simulated a background fetch via XCode it worked, whether with the emulator or a real device. If I unplugged the phone and just used it as I usually do. I never got a notification, respectively my code doesn't get executed. The solution is very simple and I think the difference to "simulate background fetch" is that your app is in a different stage then it is in your daily routine. To make it work, simply dispatch your code on a background thread. I just wrapped my code inside:

DispatchQueue.global(qos: .background).async

and it worked.



来源:https://stackoverflow.com/questions/48913622/ios-background-fetch-not-working

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!