iOS store-and-forward framework for offline HTTP P

2019-05-26 02:46发布

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

4条回答
女痞
2楼-- · 2019-05-26 03:09

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)

查看更多
Viruses.
3楼-- · 2019-05-26 03:24

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

查看更多
看我几分像从前
4楼-- · 2019-05-26 03:32

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.

查看更多
beautiful°
5楼-- · 2019-05-26 03:33

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())
查看更多
登录 后发表回答