Make http call on iOS while offline - ios

Perhaps I have been reading the wrong stuff, but one thing that all of the literatures that I have been reading seem to agree on is that: iOS does not allow background threads to run for longer than ten minutes. That seems to violate one of the greatest principles of app development: the internet should be invisible to your users. So here is a scenario.
A user is going through a tunnel or flying on an airplane, which causes no or unreliable network. At that instant, the user pulls out my email app, composes an email, and hits the send button.
Question: How do I the developer make sure that the email is sent when network becomes available? Of course I am using email as a general example, but in reality I am dealing with a very much simple http situation where my app needs to send a POST to my server.
Side Note: on android, I use Path’s priority job queue, which allows me to set it and forget it (i.e. as soon as there is network it sends my email).
another Side Note: I have been trying to use NSOperationQueue with AFNetworking, but does not do it.

What you want to achieve can be done using a background NSURLSession. While AFNetworking is based on NSURLSession I’m not quite sure if it can be used with a background session that runs while your app doesn’t. But you don’t really need this, NSURLSession is quite easy to use as is.
As a first step you need to create a session configuration for the background session:
let config = URLSessionConfiguration.background(withIdentifier: "de.5sw.test")
config.isDiscretionary = true
config.waitsForConnectivity = true
The isDiscretionary property allows the system to decide when to perform the data transfer. waitsForConnectivity (available since iOS 11) makes the system wait if there is no internet connection instead of failing immediately.
With that configuration object you can create your URL session. The important part is to specify a delegate as the closure-based callbacks get lost when the app is terminated.
let session = URLSession(configuration: config, delegate: self, delegateQueue: OperationQueue.main)
To perform your upload you ask the session to create an upload task and then resume it. For the upload task you first create your URLRequest that specifies the URL and all needed headers. The actual data you want to upload needs to be written to a file. If you provide it as a Data or stream object it cannot be uploaded after your app terminates.
let task = session.uploadTask(with: request, fromFile: fileUrl)
task.resume()
To get notified of success or failure of your upload you need to implement the URLSessionDataDelegate method urlSession(_:task:didCompleteWithError:). If error is nil the transfer was successful.
The final piece that is missing is to handle the events that happened while your app was not running. To do this you implement the method application(_:handleEventsForBackgroundURLSession:completionHandler:) in your app delegate. When the system decides that you need to handles some events for background transfers it launches your app in the background and calls this method.
In there you need first store the completion handler and then recreate your URLSession with the same configuration you used before. This then calls it’s delegate for the events you need to handle as usual. Once it is done with the events it calls the delegate method urlSessionDidFinishEvents(forBackgroundURLSession:). From there you need to call the completion handler that was passed to your app delegate.
The session configuration provides some more options:
timeoutIntervalForResource: How long the system should try to perform your upload. Default is 7 days.
sessionSendsLaunchEvents: If false the app will not be launched to handle events. They will be handled when the user opens the app manually. Defaults is true.
Here is a small sample project that shows how everything fits together: https://github.com/5sw/BackgroundUploadDemo

Your app needs to store the data internally and then you either need something which will cause the app to run in the background (but you shouldn't necessarily add something specially if you don't already have a reason to be doing it) or to wait until the user next brings the app to the foreground - then you can check for a network connection and make the call.
Note that e-mail is very different to a POST, because you can pass an e-mail off to the system mail app to send for you but you can't do exactly the same thing with a POST.
Consider looking also at NSURLSessionUploadTask if you can use it.

In three words: you don't.
And that's actually a good thing. I certainly do not want to have to think and speculate about my last 20 apps, if they are still running in the background, using memory and battery and bandwidth. Furthermore, they would be killed if more memory is needed. How would the user be able to predict if it completed its task successfully? He can't, and need to open the app anyhow to check.
As for the email example, I'd go with showing the email as "pending" (i.e. not sent), until it transferred correctly. Make it obvious to the user that he has to come back later to fulfill the job.
While every developer thinks that his app has an extremely good reason for backgrounding, reality is, for the user in 99% it's just a pain. Can you say "task manager"? ;-)

I wrote a pod that does pretty much this - https://cocoapods.org/pods/OfflineRequestManager. You'd have to do some work listening to delegate callbacks if you want to monitor whether the request is in a pending or completed/failed state, but we've been using it to ensure that requests go out in poor or no connectivity scenarios.
The simplest use case would look something like the following, though most actual cases (saving to disk, specific request data, etc.) will have a few more hoops to jump through:
import OfflineRequestManager
class SimpleRequest: OfflineRequest {
func perform(completion: #escaping (Error?) -> Void) {
doMyNetworkRequest(withCompletion: { response, error in
handleResponse(response)
completion(error)
})
}
}
///////
OfflineRequestManager.defaultManager(queueRequest: SimpleRequest())

Related

NSURLSessionUploadTask get response data

I have some misunderstanding in using NSURLSession framework, that's why I decided to write small app from scratch without AFFramework/Alamofire.
I have an API that requires following steps to upload file:
POST file data
Get response (JSON)
Post some json fields to api/save
I have a background session with such config:
let configuration = NSURLSessionConfiguration.backgroundSessionConfigurationWithIdentifier("myBackground")
let session = NSURLSession(configuration: configuration, delegate: self, delegateQueue: nil)
I've implemented 2 methods:
func URLSession(session: NSURLSession, dataTask: NSURLSessionDataTask, didReceiveData data: NSData)
where I aggregate all data
and
func URLSession(session: NSURLSession, task: NSURLSessionTask, didCompleteWithError error: NSError?)
where I tranform this data to response object. This response object if VERY important for me.
Everything works fine, while app is in foreground, but I have problems in background.
Case 1
App crashed right after I've started to upload data. According to WWDC I need to implement
func application(application: UIApplication, handleEventsForBackgroundURLSession identifier: String, completionHandler: () -> Void)
and call this handler in didCompleteWithError method. But before calling this method I need to call api/save with data from upload response.
How can I get this data?
Case 2
Mostly similar case. User stops app while upload is in progress. Than loads app in few seconds, while session works with my task. Now session calls didReceiveData, but of course, some of data is missing. What should I do in such case? How to restore response data?
You don't mention implementing URLSessionDidFinishEventsForBackgroundURLSession (a NSURLSessionDelegate method). You really want to implement that, too. The basic process is:
In app delegate's handleEventsForBackgroundURLSession, you should:
start the background NSURLSession (which will start receiving delegate method calls associated with all of the uploads); and
save the completion handler (but do not call it, yet).
Then, in URLSessionDidFinishEventsForBackgroundURLSession (when you're done processing all of the responses), you call the completion handler you saved in handleEventsForBackgroundURLSession. (Make sure to dispatch that to the main queue.)
If you're doing all of that, when the background session is restarted, the didReceiveData calls will come in with the responses to your various uploads.
I just did a quick test, uploading five 20mb images and immediately terminating the app. Then, even though the app wasn't running, I watched the five files slowly show up on my server (obviously handled by the daemon process). When all five were done, by app was transparently restarted in the background, the handleEventsForBackgroundURLSession was called (which restarted the session), it let all of the didReceiveData calls quickly get called, and when that was done, URLSessionDidFinishEventsForBackgroundURLSession was called and my app only then called the saved completion handler.
In terms of why this isn't working for you, there's not enough to diagnose the problem. Possibilities include:
Maybe you terminated the app inappropriately. You can't kill the app by double tapping the home button and terminating the app there; you have to let it naturally terminate on it's own, or for diagnostic/testing purposes, I force it to terminate by calling exit(0) in code.
Maybe you didn't restart the session when handleEventsForBackgroundURLSession was called.
Maybe you called the supplied completion handler too soon (i.e. before URLSessionDidFinishEventsForBackgroundURLSession was called).
It's hard to say, but I suspect that there's something buried inside your implementation that isn't quite right and it's hard to say what it is on the basis of the information provided (assuming it isn't one of the above points). Unfortunately, debugging this background sessions is vexingly complicated because when the app terminates, it is no longer attached to the debugger, so you can't easily debug what happens after the app is restarted automatically by iOS). Personally, I either NSLog messages and just watch the device console (as well as watching what appears on the server), or I build some persistent logging mechanism into the app itself.
For testing Background session code it is recommended to test on a real device. When writing an app that uses NSURLSession’s background session support, it’s easy to get confused by three non-obvious artifacts of the development process:
When you run your app from Xcode, Xcode installs the app in a new container, meaning that the path to your app changes. This can confuse NSURLSession’s background session support.
Note: This problem was fixed in iOS 9; if you encounter a problem with NSURLSession not handling a container path change in iOS 9 or later, please file a bug.
Xcode’s debugging prevents the system from suspending your app. So, if you run your app from Xcode, or you attach to the process some time after launch, and then move your app into the background, your app will continue executing in situations where the system would otherwise have suspended it.
Similarly, the iOS Simulator does not accurately simulate app suspend and resume; this has worked in the past but it does not work in the iOS 8 or iOS 9 simulators.
Source: Apple Developer Forum

Debugging network communication in iOS background mode

I'm working on an iOS app which makes use of the location background mode to track user visits and then sends some data over to my server. However, I have been experiencing some weird network communication problems. The only symptom is that not all gathered data gets sent to the server.
Here is more information on the problem:
My server makes logs of everything received. There were no server-side errors and every client request was successfully logged.
The client app creates a local notification when the locationManager:didVisit: method is called. This notification appears as expected when you arrive and depart at some location. Then, it calls the server over HTTPS and posts another notification, which doesn't appear every time. The whole setup looks like this:
// This code is executed from locationManager:didVisit: when the app is in background.
let myVisit: CLVisit! = ... // the received visit
self.postLocalNotification("Visit received!", visit: myVisit)
let task = UIApplication.sharedApplication().beginBackgroundTaskWithExpirationHandler(nil)
Alamofire.request(.POST, apiMethod("visit"), parameters: params, encoding: .JSON)
.responseJSON { (request, response, JSON, error) in
// This gets executed only some time, wtf?
self.postLocalNotification("Visit reported!", visit: myVisit)
UIApplication.sharedApplication().endBackgroundTask(task)
}
Therefore, I conclude I'm doing something wrong, yet I don't see what. I have checked the article on background app execution and my app seems to comply with it. What else could I be missing?
Is your app in registered to support background mode?
Since you receive location updates, your app should qualify to be set to run in background mode. Set the "Required background mode" in your plist file.
That will let it fully run in the background and you can get rid of the beginBackgroundTask lines.
The beginBackgroundTaskWithExpirationHandler methods are typically used to request a little extra time for a current task to be completed provided that your app is in the foreground and it moves to the background in the middle of a task. To me it sounds like you want to run in full background mode.
With that said, you should still detected that your program is backgrounded and avoid running unneeded cpu intensive tasks to save battery life.

Assigning a delegate to a background job for dropbox upload

I am using Dropbox's SDK API V1 to upload files from my iOS app. The files aren't loading in real time, but rather I push them into a queue, and they get uploaded in the background.
I can't figure out for the life of me how to take DB RestClient delegate and make it respond to a completion/failure event that happens in the background. Is that even possible?
It seems (and I am new here), that delegates are meant to respond to live events on screen. Is that even an option to assign them to anything other than a UI element/view?
Update: Adding some description of what the code looks like.
There is a lot of code and it's hard for me to tell what's relevant for this question.
I am using PHPhotoLibrary.sharedPhotoLibrary().performChanges() which has a completion handler.
On success, I send an image upload request via dispatch_async(dispatch_get_main_queue()) method.
Dropbox API has this method dropboxRestClient.uploadFile(filename, toPath: pathOnDropbox, withParentRev: nil, fromPath: localFileUrl)
In all the examples that I've seen, dropboxRestClient.delegate was assigned to a UIViewController of some sort, and never to anything else.
So I am not sure how to assign it correctly, so that it recognizes events that happen in this queue.

Can I use NSURLSessionUploadTask for offline syncing tasks?

I need something similar to Facebook's offline post capabilities. Basically I want users to create content locally on the device regardless of connection state, and whenever internet becomes available it should POST/PUT to the server.
I've searched the internet for a solution and I found that NSURLSessionUploadTask can be used for POST-ing in the background. But I couldn't figure out if the following scenarios are supported:
Will my task remain in the background queue when the user is offline and will the operating system try to execute items in the queue upon reconnecting with a network?
What happens if the application is force-closed by the user or crashes?
What happens if the operation fails?
First of all, background NSURLSession allows file upload only. If that is ok for you:
The task will be in the queue until it receives a server answer.
If your app is force-closed, the task will still be executing. When the request is done, your app will be launched in non-interactive background state and receive application:handleEventsForBackgroundURLSession:completionHandler:. After you process the signal and call the completion handler or 30 second timeout, the app will be closed.
I the operation fails, you will receive URLSession:task:didCompleteWithError:
There is a good tutorial on background NSURLSessions. I suggest you to read all 4 parts of this great article.
If file upload is not an option for you, i suggest you to save information into local database and then wait for internet is reachable. (a good approach here is use of Reachability library, Alamofire allows to do that too). When internet becomes available, simply call your http requests with saved data.
We were running into connectivity issues with our internal apps, so we wrote a Swift framework that allows any network operations to be enqueued and sent whenever the device has access to the internet -
https://cocoapods.org/pods/OfflineRequestManager. You'll still have to handle the network request itself within the object conforming to OfflineRequest, but it sounds like a good fit for your use case.
The simplest use case would look something like the following, though most actual cases (saving to disk, specific request data, etc.) will have a few more hoops to jump through:
import OfflineRequestManager
class SimpleRequest: OfflineRequest {
func perform(completion: #escaping (Error?) -> Void) {
doMyNetworkRequest(withCompletion: { response, error in
handleResponse(response)
completion(error)
})
}
}
///////
OfflineRequestManager.defaultManager(queueRequest: SimpleRequest())

Action Extension - Multiple NSURLSession

Im trying to upload images from the Photo app through Action Extension. I use NSURLSession to upload it in background. Here is the code i use.
var configName = "com.myapp.uploadImage"
var config = NSURLSessionConfiguration.backgroundSessionConfigurationWithIdentifier(configName)
config.sharedContainerIdentifier = "group.myApp.sample"
var session = NSURLSession(configuration: config)
let task = session.dataTaskWithRequest(request)
task.resume()
self.extensionContext!.completeRequestReturningItems(self.extensionContext!.inputItems, completionHandler: nil)
It works fine.
The question is when i upload an image and dismiss the view once and then again try uploading a second image while the initial process is still running in the background, the initial NSURLSession isn't completed. Only the second process gets completed. In short, the second session overcomes the first session.
I tried using NSOperationQueue. But action extension once dismissed and opened again for the second session, it just creates a new NSOperationQueue and hence the problem still persists.
Any suggestion will be helpful. Thanks in advance.
Make sure you don't attempt to instantiate a second background session with the same identifier while the first is still running. Save your background session so you can use it later.
As the "Background Session Considerations" of the URL Loading System Programming Guide: Using NSURLSession says:
Note: You must create exactly one session per identifier (specified when you create the configuration object). The behavior of multiple sessions sharing the same identifier is undefined.
Note, this document also mentions that one "must" specify and implement the delegate. (If nothing else, how will you know about failure if you don't do that?) The example provided in the Performing Uploads and Downloads section of the App Extension Programming Guide specifies the delegate, too.
Also, has your main app's app delegate implemented the handleEventsForBackgroundURLSession method? You have to capture the completionHandler and call it when the NSURLSessionDelegate method URLSessionDidFinishEventsForBackgroundURLSession is called.
Finally, I notice that you're using data task. The NSURLSession documentation is specific that one should not be using data tasks with background sessions, only upload/download tasks. I always assumed that was just so you don't try to use didReceiveData delegate method, but I might try using upload task just in case there's some other issue associated with data tasks with background sessions.

Resources