I got the iOS BackgroundFetch working by adding the code into XCode project directly. But the problem with Background fetch is thats background processing is completely handled by the phones OS we(developer) doesnot have any control over it.
here is the steps / code on getting it implemented in unity/xcode
Step 1:
Go to project setting and select/enable Background Behaviours
Unity—>Edit—>ProjectSetting—> Players —> Background Behaviours (Enable it or make it custom)
Doing this will provide you with the multiple options, select following
- Background Fetch
- Location Updates
- Remote Notifications(if you need it)
Step 2:
Build xCode project, and go into UnityAppController.mm
Add below code in “didFinishLaunchingWithOptions() in AppController class
Note: Its ObjectiveC Code
[[UIApplication sharedApplication] setMinimumBackgroundFetchInterval: UIApplicationBackgroundFetchIntervalMinimum ];
Step 3:
Add the following function in AppController class
Note: Its ObjectiveC Code
- (void) application:(UIApplication *)application performFetchWithCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler
{
::printf("\n\n\n ------->>>>>> Background Fetch! <<<<<<-------- \n\n\n");
// fetching the data here ...
NSString *urlString = [NSString stringWithFormat:
@"www.google.com"];
NSURLSession *session = [NSURLSession sharedSession];
[[session dataTaskWithURL:[NSURL URLWithString:urlString]
completionHandler:^(NSData *data,
NSURLResponse *response,
NSError *error) {
NSHTTPURLResponse *httpResp = (NSHTTPURLResponse*) response;
if (!error && httpResp.statusCode == 200) {
//---print out the result obtained---
NSString *result =
[[NSString alloc] initWithBytes:[data bytes]
length:[data length]
encoding:NSUTF8StringEncoding];
NSLog(@"%@", result);
//---Call out your respective Code to perform actions as per your returned data---
completionHandler(UIBackgroundFetchResultNewData);
NSLog(@"Background fetch completed...");
} else {
NSLog(@"%@", error.description);
completionHandler(UIBackgroundFetchResultFailed);
NSLog(@"Background fetch Failed...");
}
}
] resume
];
}
Just run the code on the device. You can test the BG fetch even in xCode by Running the code.
Make sure your are connected to the App and app is running from xCode
Come out of the app. by pressing home button
Now go to debug menu and click on Simulate Background Fetch option.(In the img its disabled as im not running the app).
You can see the logs getting printed in console even when the app is in BG mode.
Hope its helpful for someone else.
Also Im no expert in iOS native anymore, so there might be a better and more efficient way of doing this. If you find more better way than please share ur knowledge here as well. it might help our fellow developer.
Best of luck and happy coding.
Regards,
ABGamers.