BGProcessingTask Perform Bluetooth Connection with Core Bluetooth in Swift iOS

268 Views Asked by At

When app goes to background I wanted to connect bluetooth device with Core Bluetooth, With BGProcessingTaskI was able to perform background task(it executes after 15 min keeping app in background) but connection is not happening it didn't trigger CBCentralManagerDelegatemethods.

Here is what I've tried.

  1. I have enabled necessary Background Modes in Capabilities. enter image description here

  2. Added required things in info.plist. enter image description here

  3. When app launches I'm registering BGProcessingTask as below.

class AppDelegate: UIResponder, UIApplicationDelegate {
    
    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
        // Override point for customization after application launch.
        BGTaskScheduler.shared.cancelAllTaskRequests()
        BGTaskScheduler.shared.register(forTaskWithIdentifier: "com.myAppTest.backgroundsync", using: nil) { task in
            // Downcast the parameter to an app refresh task as this identifier is used for a refresh request.
            print("background task triggered")
            if let appRefreshTask = task as? BGProcessingTask {
                self.handleBackgroundSync(task: appRefreshTask)
            }
        }
        return true
    }
}
  1. When app goes to background will submit request and after 15 min it starts executing task handleBackgroundSync function.
    func sceneDidEnterBackground(_ scene: UIScene) {
        print(#function)
        (UIApplication.shared.delegate as! AppDelegate).scheduleBackgroundRefresh()
    }
    func scheduleBackgroundRefresh() {
        let request = BGProcessingTaskRequest(identifier: "com.myAppTest.backgroundsync")
        //        request.earliestBeginDate = Date(timeIntervalSinceNow: 1 * 60) // Fetch no earlier than 15 minutes from now
        request.requiresNetworkConnectivity = true // Need to true if your task need to network process. Defaults to false.
        request.requiresExternalPower = true
        do {
            print("App send to background")
            try BGTaskScheduler.shared.submit(request)
        } catch {
            print("Could not schedule app refresh: \(error)")
        }
    }
  1. In the handleBackgroundSync function as usual I'm trying to connect bluetooth device with Core Bluetooth. With breakpoint can debug upto scanning but CBCentralManagerDelegate delegates methods are not triggering and when I come to foreground then it triggers.
// Establish bluetooth Connection.
func handleBackgroundSync(task: BGProcessingTask) {
    task.expirationHandler = {
        print("Request expired")
    }
    // Here establishing bluetooth connection and once task is completed marking task as completed.
    // Connection is with Core Bluetooth as usual, but Can't share that piece of code. 
    // Wanted to know the steps to establish proper bluetooth connection. 
}

With the BGProcessingTask can someone please suggest a way to establish bluetooth connection.

0

There are 0 best solutions below