0

I'm trying to implement Background Fetch in my app.

Consider this function:

func fetchAll(completion: @escaping (UIBackgroundFetchResult) -> Void){

    DispatchQueue.global(qos: .background).async {
        let dGroup = DispatchGroup()

        dGroup.enter()
        self.asyncFunc1 { _ in
            dGroup.leave()
        }

        dGroup.enter()
        self.asyncFunc2 { _ in
            dGroup.leave()
        }

       ...

        dGroup.notify(queue: DispatchQueue.global(qos: .background)) {
            print("All network requests completed")
            completion(.newData)
        }
    }
}

This function is called by

func application(_ application: UIApplication, performFetchWithCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) {
        let fetchcontroller = apiHandler()
        fetchcontroller.fetchAll { (result) in
            completionHandler(result)
        }

        completionHandler(.noData)

    }

in my AppDelegate.

While testing this in the Simulator, I see the following happening:

When my app is in the foreground, fetchAll is executed successfully. However, when I have sent my app to the background, the execution is suspended, until the app is brought back to the foreground.

I guess it has to do with my wobbly knowledge of dispatch queues.

Could any of you help me out here

Sjakelien
  • 2,255
  • 3
  • 25
  • 43

1 Answers1

1

So, what I did to make this work, and I'm a bit puzzled as to why it works:

I just moved the methods inside my

performFetchWithCompletionHandler

as such:

func application(_ application: UIApplication, performFetchWithCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) {
        let fetchcontroller = apiHandler()
        let dGroup = DispatchGroup()
        dGroup.enter()
        fetchcontroller.asyncFunc1 { _ in
            dGroup.leave()
        }

        dGroup.enter()
        fetchcontroller.asyncFunc2 { _ in
            dGroup.leave()
        }

        ...

        dGroup.notify(queue: DispatchQueue.global(qos: .background)) {
            print("All 3 network requests completed")
            completionHandler(.newData)
        }

    }

Hope this helps someone

Sjakelien
  • 2,255
  • 3
  • 25
  • 43