POST request failing only when app goes in to background.

I'm trying to troubleshoot what is going on with my app. The app works just fine when the user is logged in. It's able to post data to my REST API just fine. But when the app goes in to the background, the BGAppRefreshTask fires off just fine, but it's unable to post its data. There payload is super small a two keys and two short strings and thats it.

I've tried searching on kCFStreamErrorCodeKey -2103 and ErrorDomainKey 4 but not much comes up.

Here is my error with the URL string altered...

Error Domain=NSURLErrorDomain Code=-1001 "The request timed out." UserInfo={_kCFStreamErrorCodeKey=-2103, _NSURLErrorFailingURLSessionTaskErrorKey=LocalDataTask <3126EFA1-00D3-4423-A31B-D40AB900292D>.<1>, _NSURLErrorRelatedURLSessionTaskErrorKey=( "LocalDataTask <3126EFA1-00D3-4423-A31B-D40AB900292D>.<1>" ), NSLocalizedDescription=The request timed out., NSErrorFailingURLStringKey=https://my.example.com/myapi/v1/device, NSErrorFailingURLKey=https://my.example.com/myapi/v1/device, _kCFStreamErrorDomainKey=4}

I've tried searching on kCFStreamErrorCodeKey -2103

You mean find this (-: Sadly, it doesn’t help you much.

But when the app goes in to the background, the BGAppRefreshTask fires off just fine, but it's unable to post its data.

I see two possibilities here:

  • Your app is getting suspended.

  • There’s something weird about the network environment.

Let’s start with the first:

  • Do you see the task expiration handler called?

  • Are you perhaps completing the task, by calling setTaskCompleted(success:), before the networking is done?

In this situation I recommend that you confirm these assumptions by adding log points to the relevant parts of your code. It’s best to log to the system log. See Your Friend the System Log for advice on that.

Share and Enjoy

Quinn “The Eskimo!” @ Developer Technical Support @ Apple
let myEmail = "eskimo" + "1" + "@" + "apple.com"

Thank you, it looks like since I was calling setTaskCompleted right after calling my post function; and that caused it to not complete the URLSession call.

I added a semaphore to wait til the URLSession task completes and thats did the trick.

POST request failing only when app goes in to background.
 
 
Q