I am trying to make a cron that runs every X time on the iOS system so that it sends some data to the server.
I have read that there is no way to access a cron on a non-jailbroken device. Doing some research I have found that the closest thing to a cron that can be done is to use UILocalNotification
or Background Fetch
in iOS 7, although with these methods you are at the mercy of the system.
I have decided to try the Background Fetch option and have followed this guide .
The problem I am having is that it seems that this method does not enter and it never launches with the App open or in the background.
what i have tried
I have activated the Background Modes of the app by selecting the Background Fetch option as seen in the following photo:
The code I have in the AppDelegate is the following:
-(void)application:(UIApplication *)application performFetchWithCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler{
NSDate *fetchStart = [NSDate date];
NSLog(@"Background Fetch: performFetchWithCompletionHandler");
Utilidades *util = [[Utilidades alloc]init];
BOOL conexion = [util testInternetConnection];
//Se comprueba si hay conexión a Internet
if (conexion) {
//Envio la información al servidor
completionHandler(UIBackgroundFetchResultNewData);
} else {
NSLog(@"Sin conexión. No se realiza nada");
completionHandler(UIBackgroundFetchResultFailed);
}
NSDate *fetchEnd = [NSDate date];
NSTimeInterval timeElapsed = [fetchEnd timeIntervalSinceDate:fetchStart];
NSLog(@"Background Fetch Duration: %f seconds", timeElapsed);
}
Does anyone know how to make it run every X interval regardless of whether the app is running or not? What can I be doing wrong?
Well, seeing a couple of examples in some search engines, I think that the only way to get what you want is precisely with
Background Fetch
In a part of the tutorial that you followed, they tell you that you have to define
didFinishLaunchingWithOptions
that it is basically to define the frequency with which the Fetch will be working, in the particular case of that example they useUIApplicationBackgroundFetchIntervalMinimum
that it is a pre-defined value.Then define the function that will logically take care of updating the data that you need to maintain, which is the one you leave in your question
performFetchWithCompletionHandler
What you should have in this function is:
And in your
ViewController.m
definefetchNewDataWithCompletionHandler
you must have the logic that is responsible for obtaining the data as it is in the tutorial.Without forgetting that to test this you must follow some steps: 1)
2) 3)