iOS background uploads - how to verify responses received if app crashes? - ios

When performing background uploads in iOS, is there a mechanism in place that will re-deliver upload results from the system if the app crashes while handling said results? I was hoping to see some sort of confirmation system in place telling the OS that the app has finished processing all of the data it was sent, etc but I do not see something like this in the documentation.
What I am worried about is that my users will upload 100 items and once these are all uploaded in the background my app will launch (in background mode), allowing me to handle the responses. If the app crashes while processing the response data, the other unprocessed response data is forever lost now.
This is of course an issue when doing uploads in the app as well - if you upload something and crash while handling the response you'd lose that upload (and any other uploads in flight at the time), but you risk losing way too much data in the background IMO.

For an upload task in a background session, as soon as you reconnect to the existing session by “creating” a session with the same session name, your app should get delegate calls just as though it were still running from before.
Obviously you will have to persist any app-specific data structures that tie the task’s identifier and session name to the specific content you’re uploading, since anything previously in memory is obviously gone at that point.

Related

Uploading video files while iOS app is in background?

I'm currently working on an iOS app which involves recording and uploading videos (from the built-in camera) to a server.
It all works reasonably fine and dandy, but for a new version, the customer has requested a new feature: continuing this process without needing the app to up on the screen, and active.
At present, you record a video, it's stored as an MP4 on the file system, and a background thread uploads the file to the server. This all happens while the app is open, culminating in a screen which essentially tells you to wait until the process has finished.
If you press the home button to "minimise" the app (I'm not fluent in iOS terminology, forgive me), currently all upload processes are paused. The customer wants to have it so that you can minimise and do something entirely different as this process continues, with a notification being shown once the uploads are complete.
My understanding is that iOS offers a few special cases for downloading, streaming music and location stuff.
Supposedly once upon a time you could obtain ten minutes or so of background time while your app was minimised to finish tasks - after which time iOS would forcefully pause everything until the app was front and active again. This apparently has been changed in newer versions of iOS meaning you can't rely on a specific figure anymore - but ten minutes wasn't really good enough anyway.
I can think of hacky ways of abusing the above features but I'm half-concerned Apple might discover this during the iTunes submission process. Really I'm looking for a cleaner method - how do I continue uploading videos while the app is minimised?
I am assuming there's a solution - Dropbox can handle this situation?
Surprisingly I got somewhere with this, despite quite a few guides suggesting it was virtually impossible and even Dropbox admitting it has to do a hacky location-based thing.
The code was utilising the NSURLSession class, and for uploading, you use its uploadTaskWithStreamedRequest() method, passing an HTTP request and getting a NSURLSessionUploadTask instance in return.
What wasn't immediately clear to me, however, was that "resuming" that task led to files being uploaded independently from the rest of the app, i.e. when the app is minimised, this task continues until it either completes or iOS forces it to pause.
In a sense I had already achieved what I asked for without realising, however this task can still be interrupted by iOS after a few seconds. The rest of the app is also paused, so communication is hampered until the app is brought back to the front again.
The trick is these two methods:
uploadTaskID = UIApplication.sharedApplication().beginBackgroundTaskWithExpirationHandler({})
and
UIApplication().sharedApplication().endBackgroundTask(uploadTaskID)
with these in place, any code after the "begin" function will run regardless of whether the app is minimised, and will do so until the "end" function is called. With a bit of tweaking, I've been able to get files to upload sequentially and post a notification when the process is done.
I haven't seen this solution be hinted at so it might be a bad idea, but it seemingly works.

Does the iOS platform provide background sync?

If the user performs an action in an iOS app while offline (e.g. airplane mode), can the app complete the action (by sending data to its server) once the user is online, even if the user completely closed the app before going online?
I’m asking because Twitter and Facebook do not have this functionality. (If I post something while offline, then close the app and go online, the post will not be submitted until I start the app again.)
No. If the user kills your app, it's gone. It can no longer execute any of your applications code. The best you can do is research background tasks and you then have ~10 minutes to execute your actions before it's automatically terminated (if the user doesn't do it before the OS).
You can store the actions in a Database (Core Data, Realm) or even in NSUserDefaults. When the app comes online, you can periodically attempt to parse those actions and send the network requests with exponential back-off. I imagine this is the process Facebook and Twitter use.
I disagree with #JoeyClover's answer.
If what you want to do is an HTTP POST, you should be able to set up an NSURLSession for background processing. The system should then take over submitting your post even if the app is not running. See Xcode's docs on NSURLSession for more information. (You can do the same thing for downloads with an HTTP GET, but that's not what you're asking about.)
The exception to this is if the user actually terminates your app by swiping up on it in the task list. In that case the system kills your background upload/download tasks. The info on that is in the section on NSURLSessionConfiguration. To quote Apple's docs:
Use this method to initialize a configuration object suitable for
transferring data files while the app runs in the background. A
session configured with this object hands control of the transfers
over to the system, which handles the transfers in a separate process.
In iOS, this configuration makes it possible for transfers to continue
even when the app itself is suspended or terminated.
If an iOS app is terminated by the system and relaunched, the app can
use the same identifier to create a new configuration object and
session and retrieve the status of transfers that were in progress at
the time of termination. This behavior applies only for normal
termination of the app by the system. If the user terminates the app
from the multitasking screen, the system cancels all of the session’s
background transfers. In addition, the system does not automatically
relaunch apps that were force quit by the user. The user must
explicitly relaunch the app before transfers can begin again.
(I bolded the key bit.)

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.

guaranteed delivery for uploads after network reconnect, even if my app is not running

I'm spec-ing an iOS app (which will be built outside of our company) which will upload a user's data entry to a server. If the device is not connected to the Internet, we'd like to save data on the device and upload it when the network is re-connected. (The app will primarily run on iPod Touch devices that will be disconnected most of the time).
If the user unlocks the device and re-opens our app after the network is reconnected, then uploading to the server should be easy because the app is running.
But what if the app is not running, where "not running" can mean one or more of:
device was power cycled
user has locked the device and it's sitting in his pocket
app crashed
user exited the app
user started using other apps so our app isn't running in the foreground anymore
are there other cases?
In the cases above, is there a way (ideally a battery-efficient way) to ensure that local data is uploaded soon after Internet connectivity is restored? Is the answer different depending on which of the cases above caused the app not to be running?
And is there a minimum iOS version the device will need in order to enable some (or all) of the above not-running cases to still upload when the app is not running?
My apologies if these are obvious newbie questions-- I'm not an iOS expert.
There is an interesting technique that is used by among others Instapaper and News.me(the pioneers of this technique) where you use region monitoring to initiate background downloads or uploads. Marco (Instapaper) blogged and talked (in episode 80 of the Build and Analyze podcast) about his communication with Apple so it should be a allowed in the App Store.
In brief the technique is that you set up certain regions (geofences) like "home" or "work" and respond to the locationManager:didEnterRegion: (and similar) callback(s). Your app will wake up from the background once you enter the pre-specified region and you can check to see if there is any data to upload.
This technique won't guarantee that the data is uploaded when the network reconnects but it will allow your app to automatically upload the information when the iPod Touch users gets home to their WiFi network.
That should most likely be at least once a day which may or may not be frequent enough for you. You could add a timestamp to when the initial upload was attempted and send that along the upload once it succeeds to get the correct order of events (data entries) on your server.
There is no way to ensure this. If your application is "not running" (by the definition described in your question), it will not be capable of responding to a change in the device's network status. It should be setup to resume upload operations the next time the application runs again.
EDIT:
Some of the cases you've described may indeed provide different opportunities for your application. Specifically, if the user "exits" the app by pressing the home button or launches another app in the foreground, your application may continue to run the in the background and could potentially respond to a change in network reachability.
The nature of what may be done in the background and for how-long is well documented, and supported by any version of iOS that supports multi-tasking. I recommend you review the documentation pertaining to App States and Background Services.
device was power cycled --> really NO WAY of resuming, unless you open the App!!!
user has locked the device and it's sitting in his pocket --> apps applicationStatus is UIApplicationStateInactive but it is running in the background. You still are able to react to notifications and i.e. accelerometer events. Try the Reachability Class and Log the changes!
app crashed --> NO WAY, unless opening the App
user exited the app --> App is sitting in the background. There you have a maximum of 10 Minutes Restriction of fully using your App (like the App "Pastebot" does)
user started using other apps so our app isn't running in the
foreground anymore --> Same as user exited the app
On multitasking Apple says the following:
Real multitasking only for certain kinds of usage, as there is Audio Background playing, VOIP (like Skype), navigation applications
All the other apps can request a specific amount of time after the app is closed/in the background, to finish certain tasks (as sending an email, sms or uploading/downloading important data)
Important Quote from dev docs:
Your app delegate’s applicationDidEnterBackground: method has approximately 5 seconds to finish any tasks and return. In practice, this method should return as quickly as possible. If the method does not return before time runs out, your app is killed and purged from memory. If you still need more time to perform tasks, call the beginBackgroundTaskWithExpirationHandler: method to request background execution time and then start any long-running tasks in a secondary thread. Regardless of whether you start any background tasks, the applicationDidEnterBackground: method must still exit within 5 seconds.
If you're building a restful API then I would recommend using RestKit, it has a request queue that checks the network status on the device and starts uploading once network access has been assured. You can read more about this here: http://mobile.tutsplus.com/tutorials/iphone/advanced-restkit-development_iphone-sdk/. Read the sections about Request Queue and background download/upload. It should be noted that RestKit is a big library which has it's advantages and disadvantages. I'm not completely sure how this que works with the app lifecycle, if it saves the request que even if the app is terminated. You would have to investigate that. RestKit does support background uploading/downloading, but as already noted, I think it's impossible to do any uploading if the app is terminated and not in background state.
I wouldn't recommend using RestKit if the API isn't Rest though.
You can download and experiment with RestKit here: https://github.com/RestKit/RestKit.

ASINetworkQueue Correct Usage and Storage

I have an app that submits data using ASIFormDataRequest to a remote web site. I want to allow the user to store them for upload later if they are offline (eg: iPod touch or out of cell coverage, etc). Is ASINetworkQueue the appropriate tool to use? I imagine I would store the request in a queue belonging to the app delegate and, whenever a new submission was added or the app launched, reachability would be tested and, if good, would complete each request in the queue.
Is that logic correct? (I know it is bad practice to check reachability immediately on app launch, but I would tweak that to a good time.)
If so, my next question is, how do I get a ASINetworkQueue to persist between launches, both cold and from background? I imagine it would involve writing it to NSData and writing that to NSUserDefaults or even to file.
Thanks for any help!
If you are going to upload data asynchronously but handle offline usage, I would recommend writing the data to a local database or file and then having some sort of "uploaded at" timestamp for a status. When your app starts up you can query your local database for any objects that have not been uploaded. I don't know what your app is doing but you may find this method less error prone and better for giving proper feedback to your user through the UI.

Resources