Dan Fabulich
Dan Fabulich

Reputation: 39563

iOS store-and-forward framework for offline HTTP POST requests

Is there a way (presumably a library?) to store HTTP POST requests when the user is offline, and then transmit the POST requests when the user is back online?

(I don't need to read the server's response, except insofar as I'll want to re-queue the requests if the POST request fails.)

Upvotes: 3

Views: 1947

Answers (4)

Patrick O'Malley
Patrick O'Malley

Reputation: 101

Pretty late to the party here, but I wrote a pod for our internal apps that does pretty much exactly this - https://cocoapods.org/pods/OfflineRequestManager. The actual network request is still handled by whatever conforms to the OfflineRequest protocol, but the pod provides a simple way to enqueue the requests and ensure that they keep attempting to execute until they succeed, including saving to disk.

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())

Upvotes: 0

Dan Fabulich
Dan Fabulich

Reputation: 39563

In iOS 7, NSURLSession can do it. It can even run the request in the background when the app has stopped running.

Upvotes: 0

SwiftArchitect
SwiftArchitect

Reputation: 48514

Yes, there is such a library:

http://blog.mugunthkumar.com/products/ios-framework-introducing-mknetworkkit/

It is resilient against quits and relaunch of your app, and will keep trying to send your request until there is persistent failure (such as server down, not network down)

Upvotes: 1

Caleb
Caleb

Reputation: 124997

Is there a way (presumably a library?) to store HTTP POST requests when the user is offline, and then transmit the POST requests when the user is back online?

Rather than storing the requests themselves, I think your best bet will be to store the information needed to make each request. If you wrap the data for each request in an archivable object, you can add those objects to a queue to be sent out. That way, you can archive then entire queue (you can use a mutable array for the queue) to a file if the app shuts down, and read it back when it starts up again. Use the queue as input for a separate operation that does nothing but take objects from the queue and send the corresponding requests when the device is online.

Upvotes: 0

Related Questions