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

时光总嘲笑我的痴心妄想 提交于 2019-12-22 09:55:47

问题


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


回答1:


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)




回答2:


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.




回答3:


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




回答4:


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


来源:https://stackoverflow.com/questions/16116810/ios-store-and-forward-framework-for-offline-http-post-requests

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!