How to call a method data, only when app is in background, with a time interval of one hour


I want to refresh my app data, <em>when app is in background after every one hour</em>, but only when app is in background. Earlier I was doing that on a button tap. I was calling an API on the button tap, but now I want the same when my app goes in background after every one hour. Is it possible to do that.

I have tried the below code for calling that method, but it is not getting called in background.

NSTimer* dataTimer = [NSTimer scheduledTimerWithTimeInterval:5.0 target:self selector:@selector(autoRefreshAppData) userInfo:nil repeats:YES];


Two options: BackgroundFetch or silent Push Notification.

Find more details <a href="https://stackoverflow.com/a/40328936/1457385" rel="nofollow">here</a>.


<strong>Downloading Content in the Background</strong>


Yes it is possible.


You primary have the options to use a scheduled task or execute a code block with a push notification. In my opinion it's easiest with a scheduled task, but I have have experienced that the task is not always executed. So if your app rely on the background fetch you should check if the data is downloaded at application:willEnterForeground and download data if new data is not available.

Here's the link to the Objective-c documentation on the topic: <a href="https://developer.apple.com/library/content/documentation/iPhone/Conceptual/iPhoneOSProgrammingGuide/BackgroundExecution/BackgroundExecution.html" rel="nofollow">Background Execution</a>



The process for creating a configuration object that supports background downloads is as follows:

<ol><li>Create the configuration object using the backgroundSessionConfigurationWithIdentifier: method of NSURLSessionConfiguration.</li> <li>Set the value of the configuration object’s sessionSendsLaunchEvents property to YES.</li> <li>if your app starts transfers while it is in the foreground, it is recommend that you also set the discretionary property of the configuration object to YES.</li> <li>Configure any other properties of the configuration object as appropriate.</li> <li>Use the configuration object to create your NSURLSession object.</li> </ol>

Once configured, your NSURLSession object seamlessly hands off upload and download tasks to the system at appropriate times. If tasks finish while your app is still running (either in the foreground or the background), the session object notifies its delegate in the usual way. If tasks have not yet finished and the system terminates your app, the system automatically continues managing the tasks in the background. If the user terminates your app, the system cancels any pending tasks.

When all of the tasks associated with a background session are complete, the system relaunches a terminated app (assuming that the sessionSendsLaunchEvents property was set to YES and that the user did not force quit the app) and calls the app delegate’s application:handleEventsForBackgroundURLSession:completionHandler: method. (The system may also relaunch the app to handle authentication challenges or other task-related events that require your app’s attention.) In your implementation of that delegate method, use the provided identifier to create a new NSURLSessionConfiguration and NSURLSession object with the same configuration as before. The system reconnects your new session object to the previous tasks and reports their status to the session object’s delegate.


Since I code using Swift I'll provide some documentation on that. <em>Swift 3.0</em>

<ol><li><strong>Create a Scheduler</strong></li> </ol><blockquote>

To initialize a scheduler, call init(identifier:) for NSBackgroundActivityScheduler, and pass it a unique identifier string in reverse DNS notation (nil and zero-length strings are not allowed) that remains constant across launches of your application.

</blockquote> let activity = NSBackgroundActivityScheduler(identifier: "com.example.MyApp.updatecheck") <blockquote>

The system uses this unique identifier to track the number of times the activity has run and to improve the heuristics for deciding when to run it again in the future.

</blockquote> <ol start="2"><li><strong>Configure Scheduler Properties</strong></li> </ol>

There's several properties you could configure, check the API reference for that. E.G:


Scheduling an activity to fire once each hour

</blockquote> activity.repeats = true activity.interval = 60 * 60 <ol start="3"><li><strong>Schedule Activity with scheduleWithBlock:</strong></li> </ol><blockquote>

When your block is called, it’s passed a completion handler as an argument. Configure the block to invoke this handler, passing it a result of type NSBackgroundActivityScheduler.Result to indicate whether the activity finished (finished) or should be deferred (deferred) and rescheduled for a later time. Failure to invoke the completion handler results in the activity not being rescheduled. For work that will be deferred and rescheduled, the block may optionally adjust scheduler properties, such as interval or tolerance, before calling the completion handler.

</blockquote> activity.scheduleWithBlock() { (completion: NSBackgroundActivityCompletionHandler) in // Perform the activity self.completion(NSBackgroundActivityResult.Finished) }

<strong>Notes to remember:</strong>


Apps only get ~ 10 mins (~3 mins as of iOS 7) of background execution - after this the timer will stop firing. As of iOS 7 when the device is locked it will suspend the foreground app almost instantly. The timer will not fire after an iOS 7 app is locked.



  • What happens to a Redis data store if the data exceeds available ram? [duplicate]
  • Path to Images not Working in Angular 2
  • In CouchDB shows, what does 'this' refer to?
  • Gradle: assembling multiple source-sets into one jar
  • How to build an embedding layer in Tensorflow RNN?
  • Why does Haskell Pipes “use () to close unused inputs and X (the uninhabited type) to close unused o
  • Format DateTime.Now to yyyy-mm-dd
  • Access nested dictionaries in python
  • How can I automatically send the time and location through email to someone on gmail?
  • Pretty JSON retrieved from response in GoLang
  • is it convenient to urlencode all next parameters? - django
  • Alexa Dialog Model Step and dialogState is never in COMPLETED
  • Pass Events Between QML Objects
  • Assigning variable and using it in range
  • Reconstruction MSE calculation using h2o.anomaly function from H2O R package
  • I have an element that i have declared as a shadow dom but the style is affecting the other elelemts
  • layer popup with jQuery
  • Android Null pointer Exception on Button [duplicate]
  • Preventing update loops for multiple databases using CDC
  • undefined is not an object(evaluating '_this2.props.navigation.navigate') Alert.alert
  • Access IPV6 with IPV4 [closed]
  • best way to remove the first word in a string in Java
  • AngularJS ng-repeat img ang video
  • Http Requests not getting routed to Https NodeJs
  • Displaying XML file data in a HTML table
  • Extract the data specified in brackets '[ ]' from a string message in python
  • .Net how to set IsReadOnly for a property for a usercontrol
  • Why is this Animatable property being set again?
  • Python C binding error
  • Working with codeception and laravel
  • Wrap array elements in divs based on same value
  • analytics.js event not working properly
  • Hyperlink to Outlook Attachment
  • Jenkins - could not read Username for 'https://github.com': No such device or address
  • “proxy_pass” cannot have URI part in location given by regular expression
  • Sample deviceQuery cuda program
  • Set initial vuetify v-select value
  • Ajax call on Multiple selection in Select box
  • Dynamic XML Schema Validates Subsection of Document
  • Sign a Pdf using custom digital signature in Java