Can NSURLSessionUploadTask be used for offline synchronization tasks?

I need something similar to offline messaging capabilities on Facebook. Basically, I want users to create content locally on the device, regardless of the state of the connection, and whenever access to the Internet becomes available, it should send a POST / PUT to the server.

I searched the internet for a solution, and I found that NSURLSessionUploadTask can be used for POST-IN in the background. But I could not understand if the following scenarios are supported:

  • Will my task remain in the background when the user is offline, and will the operating system try to execute items in the queue when reconnecting to the network?
  • What happens if the application is forcibly closed by the user or crashes?
  • What happens if the operation fails?
+6
source share
2 answers

First of all, background NSURLSession allows NSURLSession to upload files only. If this suits you:

  • The task will be in the queue until the server receives a response.
  • If your application is forcibly closed, the task will still be executed. When the request is completed, your application will be launched in a non-interactive background state and will receive application:handleEventsForBackgroundURLSession:completionHandler: After processing the signal and calling the completion handler or 30-second timeout, the application will be closed.
  • When the operation is completed, you will get URLSession:task:didCompleteWithError:

NSURLSessions there is a good tutorial . I suggest you read all 4 parts of this wonderful article. If downloading files is not an option for you, I suggest you save the information in a local database, and then wait for access to the Internet to be possible. (a good approach here is to use the Reachability library, Alamofire allows you to do this too). When Internet access becomes available, simply call your http requests with the saved data.

+1
source

We encountered connection problems with our internal applications, so we wrote a Swift structure that allows you to perform any network operations and send them whenever the device has Internet access - https://cocoapods.org/pods/OfflineRequestManager . You still have to process the network request on its own in the object corresponding to OfflineRequest, but it sounds like it is suitable for your use case.

The simplest example of use will look something like this: although most actual cases (saving to disk, specific request data, etc.) will have a few more hoops:

 import OfflineRequestManager class SimpleRequest: OfflineRequest { func perform(completion: @escaping (Error?) -> Void) { doMyNetworkRequest(withCompletion: { response, error in handleResponse(response) completion(error) }) } } /////// OfflineRequestManager.defaultManager(queueRequest: SimpleRequest()) 
0
source

Source: https://habr.com/ru/post/989010/


All Articles