How to troubleshoot iOS background app fetch not working?

前端 未结 2 824
小蘑菇
小蘑菇 2020-12-13 05:01

I am trying to get iOS background app fetch to work in my app. While testing in Xcode it works, when running on the device it doesn\'t!

  • My test device is runn
2条回答
  •  Happy的楠姐
    2020-12-13 05:22

    In order to implement background fetch there are three things you must do:

    • Check the box Background fetch in the Background Modes of your app’s Capabilities.
    • Use setMinimumBackgroundFetchInterval(_:) to set a time interval appropriate for your app.
    • Implement application(_:performFetchWithCompletionHandler:) in your app delegate to handle the background fetch.

    Background Fetch Frequency

    How frequent our application can perform Background Fetch is determined by the system and it depends on:

    • Whether network connectivity is available at that particular time
    • Whether the device is awake i.e. running
    • How much time and data your application has consumed in the previous Background Fetch

    In other words, your application is entirely at the mercy of the system to schedule background fetch for you. In addition, each time your application uses background fetch, it has at most 30 seconds to complete the process.

    Include in your AppDelegate (change the below code to your fetching needs)

    -(void) application:(UIApplication *)application performFetchWithCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler {
    
        NSLog(@"Background fetch started...");
    
        //---do background fetch here---
        // You have up to 30 seconds to perform the fetch
    
        BOOL downloadSuccessful = YES;
    
        if (downloadSuccessful) {
            //---set the flag that data is successfully downloaded---
            completionHandler(UIBackgroundFetchResultNewData);
        } else {
            //---set the flag that download is not successful---
            completionHandler(UIBackgroundFetchResultFailed);
        }
    
        NSLog(@"Background fetch completed...");
    }
    
    - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
    {
        [[UIApplication sharedApplication] setMinimumBackgroundFetchInterval:UIApplicationBackgroundFetchIntervalMinimum];
        return YES;
    }
    

    To check if Background Refresh is enabled for your app use the below code:

    UIBackgroundRefreshStatus status = [[UIApplication sharedApplication] backgroundRefreshStatus];
    switch (status) {
        case UIBackgroundRefreshStatusAvailable:
        // We can do background fetch! Let's do this!
        break;
        case UIBackgroundRefreshStatusDenied:
        // The user has background fetch turned off. Too bad.
        break;
        case UIBackgroundRefreshStatusRestricted:
        // Parental Controls, Enterprise Restrictions, Old Phones, Oh my!
        break;
    }
    

提交回复
热议问题