google1254 google1254 - 7 months ago 47
iOS Question

iOS: Why is fetch background function never fully executed?

My code in appdelegate for background fetch is never fully run. I have the background fetch option turned on and the plist updated.

I trigger the code by pressing Debug > Simulate Background Fetch

This is the code

func application(application: UIApplication, performFetchWithCompletionHandler completionHandler: (UIBackgroundFetchResult) -> Void) {
User.getNotifications(User.getUserDetails()["id"].string!, callback: {(notifications) in
//update notification badge count
notificationBadgeCount = X

'User.getNotifications' looks like this

getNotifications(id: String, callback...){
alamofire.request(.GET....){ jsonResponse in


When triggering the simulated background fetch, the alamofire GET request is sent and data is returned (I've checked the server and the call is sent), however, the app seems to suspend at (//GETS HERE) in the getNotifications call, so the rest the code in the background fetch (//update notification badge count) is never run.

The code seems to time out. I'm supposed to get 30s however it seems to time out in 5s or something.

Any idea why that section of code isn't executed?

NOTE: If I re-open the app manually, then the rest of the code executes.


performFetch has an incoming function called completionHandler. You must call that function to complete the fetch and stop the countdown clock. You are not doing that and you thus are timing out and the app is suspended.