how to handle a long wait time for data, when ios 8+ app has been backgrounded by user - ios

I've spent a lot of time looking at the options but am still not 100% clear, so wanted to reach out for some guidance.
Scenario is this:
User submits an HTTPS request to our backend server for some data via an iOS app
Depending on the data, the first (only) request can take a REALLY long time. like, say, 10+ minutes (shocking i know)
When that payload finally does become available and is returned via the HTTPS request, we then want to use it to update the UI in background.
The assumption here is that the user has moved on to another app whilst waiting for the data to arrive (and lets also assume they haven't killed the app).
Is it possible to handle this via iOS 8+ API's without the app being force/killed by Apple when in the background ?
Could we use background task for example?
var backgroundTask: UIBackgroundTaskIdentifier
xxx.beginBackgroundTaskWithName...
etc
Before testing some code blocks we just wanted to see if someone has (a) already done this and/or (b) whether we're heading in the right direction
Thanks for your help.

You should re-think on your web service which may take almost 10 min to process. If you are not able to optimize server task processing time then below one of the idea may be help you.
You can divided your one request into multiple request to reduce processing time and get response in faster way.
Your server should sent notification to app when its done with its task. So app will came to know task is done.
I am not sure why you try to update UI when apps in background mode , you may try to update UI when users come to foreground mode from background mode.
Please check this link which show as example of long running task. Where its use a blank audio play to keep alive app background task.

You can used "Background fetch" functionality.
For learning purpose you can refer this link

Related

Periodic background synchronization

Im quite new to iOS programming and now want to implement a periodic background synchronization to synchronize my server data with client data. What I want to achieve is comparable with Androids SyncAdapter where you can define a time interval (for example each 30 minutes) and the system will trigger the defined task automatically in the background.
Until now I could not find such mechanism for Swift 3.0 so I need to ask if somone has experience or some hints for me how I can achieve this.
What I want to do sounds quite simple:
When the app starts for the first time the app should setup a sync manager which automatically triggers a background task every 30 minutes. The background task is responsible to synchronize server and client data (using Alamofire).
How can I do that?
There is an iOS feature called BackgroundFetch, which you can set up for
regularly downloads and processes small amounts of content from the network
You can setup a minimumBackgroundFetchInterval.
In contrast to the mentioned Android feature, this interval is not guaranteed though.
The OS does some heuristic in a blackbox. It rewards you for using a "reasonable" (to the OS) CPU time/ power consumption and also for being used often by the user. On the other hand you get punished for draining the battery or (even worse) never being used/opened by the user.
See: Apple Sample and Apple Docs
Update: Since iOS13, BackgroundFetchis deprecated.
There is a similar, new API named BGTask, BGAppRefreshTask is the equivalent to deprecated BackgroundFetch.
See Apple Docs
Alternatively, depending on your needs, you can post a Silent (push) Notification whenever the users data changes on server side. A silent push wakes up your app without notifying the user, so you can fetch data and maybe inform the user by scheduling a local notification.
See: Apple Documentation
You can't. Apple doesn't allow 3rd party apps to have regular background time like that. You'll need to come up with another approach like implementing a silent push notification from your server when new content is available.
As #ekscrypto points out in their comment, you can use Background fetch to load small amounts of data when the system decides to fetch it. However, you don't have any control over when that fetching takes place. Search on "Fetching Small Amounts of Content Opportunistically" in the Xcode help system for more information.

How do bring my App "up to date" - background fetch?

I am looking for a good way how to make my app "upToDate". These are my requirements:
I have an RESTful Webservice, with tasks for different users. Every user has an iOS App, which should get automatically updated when the Server/Service assigned a task to that User.
So first ill created a manuall "Sync" Button, which checks for new Tasks. Fetches the data with Alamofire, and updated the UI.
But, my goal is automatically sync if there are new tasks.
So, ill guess there are 2 different ways to solve that:
1. Make a Background Fetch (with a NStimer?) every xx Minutes and check if there are new tasks.
After checking that tutorial here:
http://www.raywenderlich.com/92428/background-modes-ios-swift-tutorial i am not sure if a background fetch is a good way to solve that. In that case the App uses an scheduler, to check once for new updates, and not every xx minutes.
So in my case i would create an NStimer in the AppDelegate (maybe in applicationDidEnterBackground) and check every xx minutes for new data (but when there are 3 days not any new task, that would be unnecessary battery consumption, or?)
2. Using Push Notifications.
My other idea is to use Push Notifications, so when there is a new task, ill send a Push Notification an manually start the sync. In my opinion that would use less battery, because he will only start the sync when there is a new task available.
Generaly Questions about using Background Services
So ok, if the user finished the task, some data should be automatically uploaded to the server. Normally not a problem, with the manual sync ill check if there is something to upload. But, what if, when there is no internet connection (ill check if before uploading) - and the user do not press on "manual sync".
So i would prefer to check in my "Background Service" if ill got an Internet connection, and if yes - start uploading some data.
Ill know this is not a specific question, but ill think there are lots of users who have the same requirements and it would be great if someone can help me out whats the best way to solve that in the best and practical way.
Thanks in advance!
Background updates sound wonderful until you realise that Apple throttles them heavily: you can ask to be updated as frequently as possible, but iOS decides what that value actually means based on how often users open your app and when they do so. Apple considers background updates the kind of thing that should happen just before a user opens your app so the latest content is right there, rather than something that runs proactively in the background.
Your push notification solution is a better one, particularly if you use CloudKit to subscribe to record change events using CKSubscription and CKNotificationInfo. If you do this you'll automatically get push messages in your app, so you can get what you want with very little work. You can read my tutorial for more information on subscribing to CloudKit to get push messages.

swift/ios refreshing app data when in background

I'm writing a iOS/Swift application which reads data from a REST service each X minutes and updates the UI accordingly.
Now I would like that when the app is put in the background, a task keeps being invoked at X minutes intervals reading from the REST service and, in case the data just read satisfies a given condition, show a notification prompting the user to bring the app back to the foreground.
In my searches I've read that during applicationDidEnterBackground event, I should start a task with beginBackgroundTaskWithExpirationHandler.
The problem is that, if I've understood correctly, this allows a maximum of 10/15 minutes after which the app is terminated if the task is not stopped with endBackgroundUpdateTask, while I want the task to keep polling the service indefinitely (at least until the user disable it from the app's settings)
My question is:
How is this kind of functionality performed normally? Do some common solutions or best practices exist for the solution of such a problem?
Use iOS Background Fetch feature where you can specify minimum background fetch interval. But actual interval between successive invocation of your code will be determined by iOS framework. For details checkout this link: http://code.tutsplus.com/tutorials/ios-7-sdk-working-with-background-fetch--mobile-20520
I use this approach in my app and I think it is a preferred way of doing.
You can use a local notification that can be presented from the background in case your condition is met.
Correct, iOS will eventually shut down the background process, you can't enforce continuous background activity. Use the backgroundTimeRemaining property to check how much time your application has left and try to handle it as gracefully as possible by calling endBackgroundTask so that iOS does not force kill your app.
As a solution, you could think about using remote notifications with with content-available : YES, which runs the didReceiveRemoteNotification
Have a look at the Parse.com Their local datastore is an abstraction for what you are trying to acheive.
By the way, is it really necessary to refresh in the background. If call is relatively quick, there is no need to refresh until the user open's the app. Background processes like that, using the net can be quite battery consuming when the user are not on a Wifi. So consider the use case carefully!

iOS handling initial data sync which may take several minutes

I have an iOS app that needs to sync a lot of data from the cloud to device when first installed, maybe even 2GB worth if the user wants access to everything offline. Without saying "change your design", how can I ensure this initial sync completes without too much interaction from the user?
Currently it will complete as long as they keep my app in the foreground and don't let the device go to sleep. I'd like to allow them to use other apps or let the screen turn off during this process, since it's a pretty boring thing to watch.
I've seen application:performFetchWithCompletionHandler: and
beginBackgroundTaskWithName:expirationHandler, but they only allow for a short amount of time (around 30 seconds) to complete a task. Is there something better, or do I need to complicate my design by stopping my sync every ~25 seconds, and then resume next time I'm given more time by the OS?
My app is like Microsoft Outlook, it has emails (in some case millions), contacts, calendar, and several other areas. I have different sync options to limit the amount of data, but some users want access to everything offline (yes, even emails and attachments that are 10 years old). I think they are silly, but can't argue with the end-users.
I know this is a really old question, but I suggest you use NSURLSession to download data in the background even without your app running.
You simply create an NSURLSession that uses a Background NSURLSessionConfiguration (use NSURLSessionConfiguration.backgroundSessionConfigurationWithIdentifier:) and create an NSURLSessionDownloadTask for each request you need to download.
NSURLSession will download the data even when your app is not running at all, and it will save the data as files in your app's sandbox. Implement the NSURLSession delegate methods to receive notification of the download completion, read the downloaded files and save them how you see fit.
You should check out Apple's guide on Using NSURLSession.

iOS background uploading of images

I have made an application which uploads a bunch of photos to a web server. It does so by repeated html calls, using multiple AFNetworking's AFHTPRequestOperation inside an operation queue. Right now, of the user exits the application, the queue stops. However, I want to continue the uploading queue until it's done, and then let the application go to sleep like it normally does.
I know that iOS provides a background expiration handler using "beginBackgroundTaskWithExpirationHandler" . I also know that AFURLConnectionOperation which is superclass of every HTTP operation class in AFNetworking can use that using
- (void)setShouldExecuteAsBackgroundTaskWithExpirationHandler:(void (^)(void))handler
But is there any way of making this work with an operation queue? Will setting the expiration handler of each operation do the job properly if I want to upload, let's say 10 photos?
I would appreciate any comments on background tasks with AFNetworking, or if anyone has experienced the same problem as me.
When an app goes to background, the OS will decide whether or not to completely stop your app or give it some time to complete what it's doing. In case it wants your app to stop, the expiration handler is called. If that's happening you should suspend all your tasks as fast as possible and prepare for a complete kill of the app, because that is what will happen a very short time after (5 seconds max). Take a look here.

Resources