3

I'm using alamorefire to make calls to an API, but I figured that if I put the app in the background, the call will pause and I don't want that. I want it to load and then, when I bring the app to the foreground, I can use the requested data on the UI. How can this be done? At the moment I just do plain requests like this:

 Alamofire.request(url, method: .get, parameters: params, headers: header())
            .responseJSON{response in switch response.result {

I've tried using the following alamofire configuration:

let configuration = URLSessionConfiguration.background(withIdentifier: "com.cmpny.myapp.background")
        let manager = Alamofire.SessionManager(configuration: configuration)

        manager.request(url, method: .get, parameters: params, headers: headers())

This gives me the following error:

Request failed with error: Error Domain=NSURLErrorDomain Code=-999 "cancelled" UserInfo={NSErrorFailingURLStringKey=http://url, NSLocalizedDescription=cancelled, NSErrorFailingURLKey=http://url}
Recusiwe
  • 1,594
  • 4
  • 31
  • 54

1 Answers1

0

You should use UIBackgroundTaskIdentifier for this purpose.

Apple doc:

https://developer.apple.com/reference/uikit/uiapplication/1623031-beginbackgroundtaskwithexpiratio

Similar question: https://stackoverflow.com/a/31751337/1689376

Hope this helps ;)

Community
  • 1
  • 1
alexburtnik
  • 7,661
  • 4
  • 32
  • 70
  • What if my task is already started when the app goes to the background? How can I make sure it finishes? – Recusiwe Oct 09 '16 at 21:03