0

How to handle the states in which the app goes into foreground setting off a number of requests (around 3-4 minimum) because that information is required in the app, and then going to background?

What I have tried is to use a RequestManager to suspend the URLSessionDataTasks when app goes into background and when app resumes, resume those tasks again. But I don't see this working very well.

Is there a standard way to go about this?

esh
  • 2,842
  • 5
  • 23
  • 39
  • Not using Alamofire as it masks some of the errors from the APIs, where we want to take a particular action. – esh Sep 22 '18 at 08:18
  • How long do the requests take? – Paulw11 Sep 22 '18 at 08:55
  • it could take long. 2-3 of them are quite large/important APIs. (Large in the sense, return a lot of information) – esh Sep 22 '18 at 12:36
  • 1
    More than 3 minutes? You can start a background task when your app moves to the background and you have 3 minutes to complete your work. – Paulw11 Sep 22 '18 at 12:40

1 Answers1

1

Suspending tasks won't work, because the session no longer exists if your app gets jettisoned for low memory.

The most straightforward approach would be to use a download task in a background session, then read the resulting temporary file when it finishes downloading. Download and upload tasks in background sessions are the only types of tasks that can survive your app getting jettisoned while in the background because of memory pressure.

If you absolutely must avoid downloading while the app is in the background (why?), you could create a download task in either a foreground or background session, then stop the download tasks by calling cancelByProducingResumeData: when your app gets backgrounded. You can later continue the request by calling downloadTaskWithResumeData:.

There is a rather large caveat with that approach, though, which is that the resume data portions of the API are not nearly as well tested as the background downloading portions. Case in point: in every version of iOS 10 from the first beta until 10.2, support for resume data was completely broken. (There is a rather horrific workaround, in case you choose to go down that path.)

So I would recommend the first approach unless you have some contractual or legal obligation not to do so.

dgatwood
  • 10,129
  • 1
  • 28
  • 49