2017-10-30 31 views
0

백그라운드에서 BLE와 연결을 시도하고 있지만 백그라운드에서 연결하지 않았습니다. 내 앱이 포 그라운드에있을 때 작동합니다. 주변기기의 UUID로 스캔하려고합니다. 첨부 된 코드는 다음과 같습니다.신속한 백그라운드 스캔 BLE

override func viewDidLoad() { 
     super.viewDidLoad() 

     manager = CBCentralManager(delegate: self, queue: nil) 

    } 


    func centralManagerDidUpdateState(_ central: CBCentralManager) { 

     var msg = "" 

     switch central.state { 

      case .poweredOff: 
       msg = "Bluetooth is Off" 
      case .poweredOn: 
       msg = "Bluetooth is On" 
       let arrayOfServices: [CBUUID] = [CBUUID(string: "CCAExxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx")] 

       manager?.scanForPeripherals(withServices:arrayOfServices, options: nil) 
      case .unsupported: 
       msg = "Not Supported" 
      default: 
       msg = "Not Connected" 

     } 

     print("STATE: " + msg) 

    } 

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

     print("Name: \(peripheral.name)") //print the names of all peripherals connected. 

     //you are going to use the name here down here ⇩ 

     if peripheral.name == "Name of device" { //if is it my peripheral, then connect 

      self.myBluetoothPeripheral = peripheral  //save peripheral 
      self.myBluetoothPeripheral.delegate = self 

      manager.stopScan()       //stop scanning for peripherals 
      manager.connect(myBluetoothPeripheral, options: nil) //connect to my peripheral 

     } 
    } 

어떻게 해결할 수 있습니까?

+0

왜 백그라운드에서 장치에 연결 하시겠습니까? 당신이 백그라운드에서 연결할 수 있다면 당신이 원하는 것을 정확히 말해 줄 수 있습니까? – EmirC

+0

그것은 일부 데이터, 즉 하트 비트를 전송하기위한 것이거나 모든 데이터 일 수 있습니다 .i scanForPeripherals method.is에서 options 매개 변수에 nil을 지정 했습니까? – user12346

+0

장치 이름을 확인하고 무엇이 발생하는지 보려면 if를 제거하십시오. 알려진 주변 장치를 인식하려면 이름이 아닌 식별자를 사용해야합니다. 배경에서 스캔 할 때 이름을 사용할 수 없습니다. – Paulw11

답변

0

'배경 모드'기능을 켭니다.

다음 두 옵션을 켜십시오. 1. 사용자 Bluetooth LE 액세서리. 2. Bluetooth LE 액세서리로 작동합니다.

같은 스크린 샷으로 수행

enter image description here

이제 BLE은 아이폰 OS 응용 프로그램의 백그라운드 모드에서 일하고있다.

0

CentralManager를 인스턴스화 할 때 복원 식별자로 인스턴스를 생성해야합니다.

예는 :

CBCentralManager(delegate: self,options: 
[CBCentralManagerOptionRestoreIdentifierKey: "bleCentralManager"]) 

이 그것이라고 사과 설명서 필요하다 "코어 블루투스 복원 식별자가있는 경우에만 해당 객체의 상태를 유지합니다." 그런 다음

앱이 당신 안에 같은 복원 식별자 AppDelegate에의 응용 프로그램과 함께 당신의 적절한 중앙 관리자를 reinstantiate해야하는 배경으로 재발되는 : didFinishLaunchingWithOptions :

let centralManagerIdentifiers = launchOptions![UIApplicationLaunchOptionsKey.bluetoothCentrals] 
: method.You은 다음과 같이 복원 식별자를 얻을 수 있습니다

마지막으로 중앙 관리자 (중앙 : CBCentralManager, willRestoreState dict : [String : Any]) 위임 메서드에서 중앙 관리자가 연결되었거나 연결하려고하는 모든 주변 장치의 목록을 가져 와서 원하는대로 수행 할 수 있습니다 이 방법으로해라.

func centralManager(_ central: CBCentralManager, willRestoreState dict: [String : Any]) { 

    let peripherals = dict[CBCentralManagerRestoredStatePeripheralsKey] 

}