How to run timer in background for unlimited time while iphone screen locked or unlocked and calling web service

Hi there


I've read many posts about running tasks in the background, however I have not been able to get an answer to our bluetooth entitled app's problem.


We have an app that connects to a bluetooth device(Beacon) and sends and receives BLE data in the background. There is no problem when the app is in foreground, the problem we face is when the app goes background and the device is locked. Yet it is extremely important that our app is sending data through web service every 5 minutes till the user exits the region


We start a task with beginBackgroundTask, set a timer to executes after 3 minutes. But when the user enters the region, beacon is detected and if the app is in the background, only one request is sent after 3 minutes and it doesn't repeat again till the user exits the region.


func doBackgroundTask() {

DispatchQueue.global(qos: DispatchQoS.QoSClass.default).async {

self.beginBackgroundTask()

self.countdownTimer = Timer.scheduledTimer(timeInterval: 180, target: self, selector: #selector(self.requestService), userInfo: nil, repeats: true)

RunLoop.current.add(self.countdownTimer, forMode: .common)

RunLoop.current.run()

}

}


func beginBackgroundTask() {

self.backgroundTask = UIApplication.shared.beginBackgroundTask(expirationHandler: {

// you can't call endBackgroundTask here and you don't need to

})

assert(self.backgroundTask != UIBackgroundTaskIdentifier.invalid)

}


func endBackgroundTask() {

if self.backgroundTask != nil {

UIApplication.shared.endBackgroundTask(self.backgroundTask)

self.backgroundTask = UIBackgroundTaskIdentifier.invalid

}

}


How do I make the app run in the background for once in every 5 mins till the user exits the region.

Replies

You seem to have posted the same question twice (under different user names no less). I’ll respond on your later thread.

Share and Enjoy

Quinn “The Eskimo!”
Apple Developer Relations, Developer Technical Support, Core OS/Hardware

let myEmail = "eskimo" + "1" + "@apple.com"