0

I have an api call which I need to call whenever app goes in background and when it becomes active. I have placed breakpoint in the response handler. When app becomes active, control comes in breakpoint but it never does when app goes in background. Seems like api is not called. I have Background fetch enabled in project capabilities as well as following background mode key in Info.plist :

<key>UIBackgroundModes</key>
    <array>
        <string>fetch</string>
        <string>remote-notification</string>
</array>  

Api call :

let dataTask = session.dataTask(with: request, completionHandler: { (data, response, error) in
    if error != nil {
        print("Error:...")
    } else {
        let responseString = String(data: data!, encoding: .utf8)
        let data = responseString?.data(using: .utf8)!                            
        do {
            if let responseDict = try JSONSerialization.jsonObject(with: data!, options : .allowFragments) as? [String: Any] {
                self.delegate.apiClientDidFinishWithResponse(response: responseDict, forRequest: self.serviceCallType)
            } else {
                //....
            }
         } catch let error as NSError {
            print(error)                
         }
     }
 })

 dataTask.resume()
Sohil R. Memon
  • 9,404
  • 1
  • 31
  • 57
Nitish
  • 13,845
  • 28
  • 135
  • 263
  • Show the code where you make the request when your app enters the background. You probably need to call `beginBackgroundTask(expirationHandler:)` before making your call in order to get more execution time before your app is suspended – Paulw11 Jul 10 '19 at 08:14
  • Background fetch is not the functionality your looking for, you need to use a background data task instead for this call. Refer to this medium post, but replace the upload task with a regular data task, best wrap it in an NSOperation or something – Sean Lintern Jul 10 '19 at 08:21
  • @Paulw11 : Added the code – Nitish Jul 10 '19 at 08:55
  • @SeanLintern : Tried adding the above code inside DispatchQueue.global(qos: .background).async. But still didn't got called – Nitish Jul 10 '19 at 08:56
  • Yes, you definitely need to call `beginBackgroundTask(expirationHandler)` before you call `resume` and you need to call `endBackgroundTask` in the completion handler – Paulw11 Jul 10 '19 at 10:49

0 Answers0