1
votes

My app can connect in foreground to BLE devices. But BLE device doesn't re-connect again after disconnect device while the app is in background. I added required permission in info.plist :

<key>UIBackgroundModes</key>
    <array>
        <string>bluetooth-central</string>
        <string>bluetooth-peripheral</string>
    </array>

I created central manager object for scanning in HomeViewController :

   let centralManager = CBCentralManager(delegate: self, queue: nil)
   centralManager.delegate = self
   let options  = [CBCentralManagerScanOptionAllowDuplicatesKey : true]
   centralManager.scanForPeripherals(withServices:nil, options: options)

I tried scanForPeripherals with services when app in background but it doesn't work :

 let backgroundScanOptions  = [CBCentralManagerScanOptionSolicitedServiceUUIDsKey : true]
 centralManager.scanForPeripherals(withServices: [customServiceUUIDs], options: backgroundScanOptions)

What can I do for re-connect device in background ?

1

1 Answers

0
votes

swift 4

import UIKit
import CoreBluetooth

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate, CBCentralManagerDelegate, CBPeripheralDelegate{

var window: UIWindow?

        //MARK:- all variables...
var bleCentralManager: CBCentralManager!
var selectedPeripheral: CBPeripheral!
let serviceUUIDForBackgroundScanning: [CBUUID] = [CBUUID(string: "07A2715C-3B28-4F7F-8824-BA18255B2344")

func bleCentralManagerfunc(){

    self.bleCentralManager = CBCentralManager(delegate: self, queue: nil)
}

        //MARK:- CBCentralManagerDelegate methods...
func centralManagerDidUpdateState(_ central: CBCentralManager) {

    switch central.state{

        case .poweredOn:    central.scanForPeripherals(withServices: nil, options: nil)

        default: print("Please turn on Bluetooth")
    }
}

func centralManager(_ central: CBCentralManager, didDiscover peripheral: CBPeripheral, advertisementData: [String : Any], rssi RSSI: NSNumber) {

    if !(self.arrayPeripheralList.contains(peripheral)){

            self.arrayPeripheralList.append(peripheral)
    }
}

func applicationDidEnterBackground(_ application: UIApplication) {

    self.bleCentralManager.scanForPeripherals(withServices: serviceUUIDForBackgroundScanning, options: nil)
}
}