Background service

Hi! I need to send the data from coreData to server after 30 minutes even the app is in the background. Currently i'm doing it with timer but timer gets stop working when my application enters background.

Replies

What should happen if the phone is switched off before 30 minutes ?


Couldn't you do the job on the server: receive data immediately and then commit the transaction after 30 minutes ? Of course that requires that you can modify the server.


Otherwise, may have a look here:

https://stackoverflow.com/questions/42319172/swift-3-how-to-make-timer-work-in-background

I'm storing the user reviews in core data even the internet is not available and try to sync all the reviews with our server when internet is available. So currently if the app is in background I can't send the data to our server as timer gets stop when the app is background. So i need a service in background which checks after each 30 minutes that if internet is available and there are reviews pending to sync, so it sync all of them.

So i need a service in background which checks after each 30 minutes that if internet is available and there are reviews pending to sync, so it sync all of them.

iOS has no mechanism to schedule work to run at a specific time [1], but I suspect you could get a good approximation of this using

NSURLSession
background sessions. Specifically:
  1. When the user adds their first review, start an upload task in a background session and set the

    earliestBeginDate
    to 30 minutes. This task will necessarily be limited to just that review.
  2. When you get the

    -URLSession:task:willBeginDelayedRequest:completionHandler:
    delegate callback, complete that with a new task (
    NSURLSessionDelayedRequestUseNewRequest
    ) that encompasses all the current reviews.

Share and Enjoy

Quinn “The Eskimo!”
Apple Developer Relations, Developer Technical Support, Core OS/Hardware

let myEmail = "eskimo" + "1" + "@apple.com"

[1] Currently. iOS 13 beta adds the BackgroundTasks framework, which offers a whole new range of capabilities.