5

Using iOS 13.3.1 Xcode 11.3.1 Swift 5

Code says this, compiles but doesn't run correctly. When I background my app I get an error message that says "fails with no background task exists with identifier 1 or it may have already been ended".

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
BGTaskScheduler.shared.register(forTaskWithIdentifier: "ch.blah.refresh", using: nil) { (task) in
  self.handleAppRefresh(task: task as! BGAppRefreshTask)
}


return true
}

func applicationDidEnterBackground(_ application: UIApplication) {
  scheduleAppRefresh()
}

var request: BGAppRefreshTaskRequest!

func scheduleAppRefresh() {
  request = BGAppRefreshTaskRequest(identifier: "ch.blah.refresh")
  request.earliestBeginDate = Date(timeIntervalSinceNow: 60)
do {
  try BGTaskScheduler.shared.submit(request)
} catch {
  print("Could not schedule app refresh: \(error)")
}

}

func handleAppRefresh(task: BGAppRefreshTask) {
 scheduleAppRefresh()

 let queue = OperationQueue()
 queue.maxConcurrentOperationCount = 1

 queue.addOperation {
   for i in 1 ... 1000000 {
    print("\(i)")
   }
 }

 let lastOp = queue.operations.last
 lastOp?.completionBlock = {
   task.setTaskCompleted(success: !lastOp!.isCancelled)
 }

 task.expirationHandler = {
   queue.cancelAllOperations()
 }


 }

Yes, I did add the key to Info.plist

<key>BGTaskSchedulerPermittedIdentifiers</key>
<array>
    <string>ch.blah.refresh</string>
</array> 

I am getting several failures due to iOS 13. What am I missing?

I did try downloading the Apple WWDC code to take a look. But it has the same problem, it appears.

halfer
  • 19,824
  • 17
  • 99
  • 186
user3069232
  • 8,587
  • 7
  • 46
  • 87
  • 1
    Told by a colleague at Apple that you can ignore this? which I can do, but I still see nothing when I run this? is this a sane operation to try to execute? – user3069232 Feb 11 '20 at 17:15
  • 1
    I believe the error is a red herring (I am getting the same error for multiple projects on background with no adverse effects); some chatter on that here: https://forums.developer.apple.com/thread/121990 In addition the code may be fine but not executing until system decides to as discussed here: https://stackoverflow.com/questions/59454989/ios-13-using-bgtaskscheduler-doesnt-work-all-the-time – okat Feb 11 '20 at 18:33
  • I had the same issue on simulators though. But i tried this on Real device with iOS 13.4 and it really works pretty smooth. And i could able to see the task being simulated as well. https://developer.apple.com/documentation/backgroundtasks/refreshing_and_maintaining_your_app_using_background_tasks – Mahesh S Mar 27 '20 at 18:48

2 Answers2

4

Based on the error you're getting, it's possible one of these are true:

  1. trying to run your app in simulator (which doesn't support BG tasks, you have to run on your device)
  2. you didn't add the Background Modes capabilities in Xcode's project settings

Also, please note, in my experience I cant get BGAppRefreshTaskRequest to work unless I turn on BOTH "Background fetch" and "Background Processing". When I turn on just "Background fetch" nothing happens for me.

enter image description here

A second tip could be here:

request.earliestBeginDate = Date(timeIntervalSinceNow: 60)

This is scheduled 1 minute away. I had terrible luck getting anything scheduled immediately like this to fire. If I scheduled my bg task to run within the next 5 minutes, it wouldn't, but I scheduled it to run later tonight, it worked pretty consistently. This could just be anecdotal but something worth trying.

There is an Xcode console command that Apple recommends for firing your BG tasks on demand, but I've never gotten it to work, you may have better luck:

e -l objc -- (void)[[BGTaskScheduler sharedScheduler] _simulateExpirationForTaskWithIdentifier:@"com.your.task.identifier"]

William T.
  • 12,831
  • 4
  • 56
  • 53
1

try this:

let queue = OperationQueue.main
  • 3
    While this code may answer the question, providing additional context regarding why and/or how this code answers the question improves its long-term value. Consider reading [How to Answer](https://stackoverflow.com/help/how-to-answer) and [edit] your answer to improve it. – blurfus Nov 06 '20 at 18:55
  • 1
    @blurfus: While that's true, and this answer should really be updated, [code-only answers should not be marked for deletion](https://meta.stackoverflow.com/a/256360/3025856). – Jeremy Caney Nov 06 '20 at 21:29